0
int n;
cin>>n;
if(cin.fail()){
 cin.clear(); 
 cin.ignore(numeric_limits<streamsize>::max(),\n);
 cout<<"Data is not numeric";
}
else{
 cout<<n;
}



This works fine until any numeric value is entered followed by some characters like: 123ahs. here else block will also execute and cout will give me 123. So what shall i do to discard this kind of input as well?

kaya3
  • 47,440
  • 4
  • 68
  • 97
radx
  • 1
  • You can't predict the future. If 123abc is entered and you read a number you get 123, then the next time you try to read a number you get an error and your error handling code would be executed. If the next input was a string it would work just fine. – Retired Ninja Jun 15 '22 at 17:50
  • How do you (as a human) recognise input which you want to ignore? Keep in mind that the input might not be interactive and that while the current bit is gibberish, the later input which you do want to read is already in the flow. So, how can you look at and throw away anything not matching what you expect? – Yunnosch Jun 15 '22 at 17:51
  • Why you can't receive input as string? then use stoi() function within try catch block – user19139505 Jun 15 '22 at 17:55
  • 1
    Note: `stoi`, if left to the defaults, will still produce 123 from *123ahs* and generate no exception. If you want to reject the input completely, you need to monitor the argument used as [the `pos` parameter](https://en.cppreference.com/w/cpp/string/basic_string/stol) to ensure the entire string was consumed. – user4581301 Jun 15 '22 at 18:44

0 Answers0