0
cin >> num; while (cin.fail() || num < 0 || num > 999999) // child proofing { cout << " ERROR: wrong/invalid input try again "; cin.clear(); // reset any flag errors in the cin cin.ignore(INT_MAX, '\n'); cin >> num; } 

if I enter a combination of integers and letters it will ignore the letters and input the numbers

Input: 1234ekl Output: 1234 Input: 12wr43 Output: 12 

I need a way to check the input so I could as for a valid one in case its not.

2
  • Consider using getline(). Also, consider using something like Test Driven Development to make sure cases are handled correctly. As a new user here, also take the tour and read How to Ask. BTW: The formatting of your code is a bit messed up, edit your question to fix that. Commented Jan 26, 2021 at 8:22
  • Another duplicate: stackoverflow.com/q/10828937/1025391 Commented Jan 26, 2021 at 8:37

1 Answer 1

0

The operator>> immediately parses the input data, you cannot intervene in that. You can, however, scan an entire input line and check for any illegal characters, like this:

std::string str; // scans the entire line std::getline(std::cin, str); // checks for existence of any invalid characters // refer to http://www.cplusplus.com/reference/string/string/find_first_not_of/ if(str.find_first_not_of("0123456789") != std::string::npos) { [handle the error] } // parse the string when you know it is valid else { int result = std::stoi(str); } 

EDIT: As suggested in the comments, here is an alternative way that uses the option to retrieve the number of characters parsed from std::stoi.

std::string str; std::size_t sz; int i; std::getline(std::cin, str); try { i = std::stoi(str, &sz); } catch(std::exception) { // failed to parse [handle the error] } if(sz != str.length()) { // parsed, but there are trailing invalid characters [handle the error] } else { // valid input was provided } 
Sign up to request clarification or add additional context in comments.

4 Comments

it'd be much simpler to just use stoi's built in error handling rather than manually checking whether the string contains non-numeric characters
@AlanBirtles stoi parses in the same way as cin, does it not? That would simply ignore non-numerics, which is exactly what we want to avoid here
it does but it has a parameter for a pointer which will contain the number of characters read
Oh... It does not. My bad. It throws on leading non-numeric characters, but not on trailing ones. Yes, it would probably be better to check the character count.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.