The loop and character in the int variable do not work as I expect

An unusual problem has appeared in this code:

#include <iostream>
using namespace std;

int main()
{
 int number;
 bool repeat=true;

 while (repeat)
 {
  cout<<"\nEnter a number:";
  cin>>number;
  cout<<"\nNumber is:"
   <<number;
  cout<<"\nRepeat?:";
  cin>>repeat;
 }
 system("pause");
 return 0;
}

here in this code when i put the character such an β€œA” into an int variable when the loop repeats over and over and don’t ask me whether to repeat or not. this problem occurs when I put characters in non-integer numbers. it also appears.

why should this happen? thank

+3
source share
2 answers

, , . clear reset , .

, ( , good() fail() ..), reset , :

std::cin.clear(); 
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');   
+3

cin , int . , , . ( if (cin β†’ number)).

0

Source: https://habr.com/ru/post/1773433/


All Articles