Avoid infinite loop when char is introduced instead of int

I am doing a banking system project and have to make sure that every entry is valid (the program must be reliable). If an invalid entry is entered, the user must enter it again.
But when I have a type variable intand the user enters char, an infinite loop begins.
For instance:

int i;
cin>>i;

If the user enters an infinite loop char. How can I avoid this and ask the user again?
Thanks

+4
source share
2 answers

, ; std::string, , , . <cctype> for isdigit() <cstdlib> for std::atoi, ++ 11 std::stoi, .

: 141.4123, 141, .., , int.

:

int str_check(string& holder, int& x)
{
  bool all_digits = true; // we expect that all be digits.

  if (cin >> holder) {
    for(const auto& i : holder) {
      if (!isdigit(i) && i != '.') { // '.' will also pass the test.
        all_digits = false;
        break;
      }
    }
    if (all_digits) {
      x = atoi(holder.c_str()); // convert str to int using std::atoi
      return 1;
    }
    else
      return 0;
  }
}

int main()
{
  int x{};
  string holder{};
  while (1)
  {
    if (str_check(holder, x))
      cout << x << '\n';
  }

  return 0;
}
+2

:

cin , , reset.

cin.clear();
cin.ignore(100, '\n'); //100 --> asks cin to discard 100 characters from the input stream.

, :

non-int int. , , char isdigit() .

isdigit() . .

is_int() .

for(int i=0; char[i]!='\0';i++){
   if(!isdigit(str[i]))
      return false;
}
return true;
+3

All Articles