Integer input check how?

I have a problem with what should be incredibly simple code. I want to take an integer from 1 to 3 with error checking. It works great for checking too large or too large numbers, but when an alpha / number combination is entered, it gets stuck in an infinite loop. Suggestions?

#include <iostream> using namespace std; int main(int argc, char *argv[]){ int input; cout << "\nPlease enter a number from 1 to 3:" << endl; cout << "-> "; cin >> input; while(input< 1 || input> 3){ cout << "\n---------------------------------------" << endl; cout << "\n[!] The number you entered was invalid." << endl; cout << "\nPlease re-enter a number from 1 to 3" << endl; cout << "-> "; cin >> input; } cout << "You chose " << input << endl; } 
+4
source share
4 answers

The problem is that:

 cin >> input; 

Will cause the wrong bit when you try to read a non-numeric value. After that, any attempt to use operator>> ignored.

So, the way to fix this is to check if the thread is in good condition, and if not, reset the status flags and try and read it again. But note that bad input (which caused the problem) is still at the input, so you need to also make sure you throw it away too.

 if (cin >> input) { // It worked (input is now in a good state) } else { // input is in a bad state. // So first clear the state. cin.clear(); // Now you must get rid of the bad input. // Personally I would just ignore the rest of the line cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // now that you have reset the stream you can go back and try and read again. } 

To prevent a jam (caused by the wrong bit), read the line, then use the string stream to analyze user input. I also prefer this method (for user interactive input), because it allows you to simplify the combination of different reading styles (i.e. combine operator>> and std::getline() , as you can use them in a string stream).

 #include <iostream> #include <sstream> #include <string> // using namespace std; // Try to stop using this. // For anything other than a toy program it becomes a problem. int main(int argc, char *argv[]) { int input; std::string line; while(std::getline(std::cin, line)) // read a line at a time for parsing. { std::stringstream linestream(line); if (!(linestream >> input)) { // input was not a number // Error message and try again continue; } if ((input < 1) || (input > 3)) { // Error out of range // Message and try again continue; } char errorTest; if (linestream >> errorTest) { // There was extra stuff on the same line. // ie sobody typed 2x<enter> // Error Message; continue; } // it worked perfectly. // The value is now in input. // So break out of the loop. break; } } 
+6
source
 #include <iostream> #include <string> using namespace std; int validatedInput(int min = 1, int max = 3) { while(true) { cout << "Enter a number: "; string s; getline(cin,s); char *endp = 0; int ret = strtol(s.c_str(),&endp,10); if(endp!=s.c_str() && !*endp && ret >= min && ret <= max) return ret; cout << "Invalid input. Allowed range: " << min << "-" << max <<endl; } } int main(int argc, char *argv[]) { int val = validatedInput(); cout << "You entered " << val <<endl; return 0; } 
+2
source

Most of these answers include unnecessary complexity.

Input validation is the perfect time to use do-while

 do{ cout << "\nPlease enter a number from 1 to 3:" << endl; cout << "-> "; if(!cin){ cout << "Invalid input" cin.clear() cin.ignore(numeric_limits<streamsize>::max(), '\n'); } }while(!(cin >> input)) 
  • Use numeric_limits<streamsize>::max() to completely clear the buffer after a failed cin .

  • Use cin.clear() to reset the failure flag to cin , so !cin Cin wont always evaluate to false.

cin.fail() excellent. However, some would consider !cin more natural.

from my previous post fooobar.com/questions/1443849 / ...

+1
source

You declared input as int, but when you write an alphanumeric character for input, it will try to implicitly convert it to an integer. But error checking does not take this into account.

Ur problem can be easily solved by changing the while loop. instead of checking this how do you check

 while(input!=1 || input!=2 || input!=3) 
0
source

Source: https://habr.com/ru/post/1443847/


All Articles