P
P
PUTINVODKAGTA2020-12-03 22:24:44
C++ / C#
PUTINVODKAGTA, 2020-12-03 22:24:44

Checking the correctness of the input data, the function does not work correctly! Where is the mistake?

The code
int check_value(int &value)
  {		
    bool check = true;
    string temp = "";		
    do
    {				
      getline(cin, temp, '\n');
      for (int i = 0; i < temp.size(); i++)
      {				
        if (temp[i] != '2' && temp[i] != '3' && temp[i] != '4' && temp[i] != '5' && temp[i] != '6'
          && temp[i] != '7' && temp[i] != '8' && temp[i] != '9' && temp[i] != '0' && temp[i] != '1'
          && temp[i] == ' ')
        {
          cout << "Ошибка! Введите корректное значение:" << endl;
          cin.clear();
          check = false;
          break;
        }
        else
        {
          check = true;
        }
      }
      
      
    } while (!check);	
    if (check)
    {
      value = stoi(temp);
      return value;
    }
  }


Good day!

There is a function that checks the correctness of the input data. It should throw an error if the entered value is not a number. The function works correctly in all cases, for example: "2 a" - error, "2 2" - error. But if you enter 2a - it does not give an error. I looked through the debugger, when it comes to "a" , it considers the value correct and does not go inside the if. What's my mistake?

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-12-03
@PUTINVODKAGTA

What's my mistake?

temp[i] == ' '

in that. Must be!=

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question