problem with cin's failbit

I have something similar to the following:
1
2
3
4
5
6
 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?
I tried to use both cin.clear() and cin.ignore() but neither seem to work.

As I understand cin.clear() just clears cin's error flags.

1
2
3
4
5
6
7
8
9
10
        int number;
 	char ch;

 	cin>>number;
 	if(!cin)
 	{
 		cout<<"Error\n";
 		cin.clear();
 	}
 	cin>>ch;

does the same thing as the original code.
I tried to use both cin.clear() and cin.ignore()
Show how you used .ignore() and what behavior you expect on this input:
123X AB
C D
Last edited on
So in kbw's example:
1
2
3
4
5
6
7
8
9
10
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.
So you need to read only one
digit
? Your program reads all consequent digits until first whitespace. Look into .get() member function.
Topic archived. No new replies allowed.