Can cin.fail() be used to detect non integer inputs?

I want to check if an input is a number or not, and only accept it if it is.
1
2
3
4
5
6
  int a;
  do{
  std::cin>>a;
  if(std::cin.fail())std::cout<<"gib number\n";
  }
  while(std::cin.fail());


Would this bit of code accomplish this?
Last edited on
Well it would, but you need some way to get rid of the bad input as well.

1
2
3
4
5
6
if ( std::cin >> a ) {
    // success
} else {
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}


See the example here
https://en.cppreference.com/w/cpp/io/basic_istream/ignore
Topic archived. No new replies allowed.