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.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • 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 [ask]. BTW: The formatting of your code is a bit messed up, [edit] your question to fix that. – Ulrich Eckhardt Jan 26 '21 at 08:22
  • Another duplicate: https://stackoverflow.com/q/10828937/1025391 – moooeeeep Jan 26 '21 at 08:37

1 Answers1

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
}
IWonderWhatThisAPIDoes
  • 1,000
  • 1
  • 4
  • 14
  • 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 – Alan Birtles Jan 26 '21 at 08:37
  • @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 – IWonderWhatThisAPIDoes Jan 26 '21 at 08:39
  • it does but it has a parameter for a pointer which will contain the number of characters read – Alan Birtles Jan 26 '21 at 08:41
  • 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. – IWonderWhatThisAPIDoes Jan 26 '21 at 08:43