int number;
char ch;
cin>>number;
if(!cin){cout<<"Error\n";}
cin>>ch;
entering a character when prompted for number triggers the cin failbit and prints "Error" but the character is then carried over and read into ch ending the program.
How do I tell it to forget the character and begin reading in a fresh line?
double n;
while( std::cout << "Please, enter a number\n"
&& ! (std::cin >> n) )
{
std::cin.clear();
std::string line;
std::getline(std::cin, line);
std::cout << "I am sorry, but '" << line << "' is not a number\n";
}
std::cout << "Thank you for entering the number " << n << '\n';
cin.clear() is used to clear the error flag but then the excess/incorrect input is dumped into a string.
Instead of dumping the excess/incorrect input into a string is there any way to tell the computer to completely forget about it?
As for the input
123X AB
C D
in this simplified program it would read the number 1 into number and '2' into ch and then be done.
suppose the input was
AB
in this case I want to say 'A' is not an int and cannot be read into number. Now forget 'A' and store 'B' in ch.