Throw the question:
Attach the code of the example program in the book first
#include <iostream>int main () {int ival;while (std::cin >> ival,!std::cin.eof ()) {if (Std::cin.bad ()) throw Std::runtime_error ("IO stream corrupted"), if (Std::cin.fail ()) {Std::cerr << bad data, try again << std:: Endl;std::cin.clear (std::istream::failbit); continue;}} return 0;}
When the input is normal, there is no problem. When you enter a letter, the word "bad data, try again" is printed, and the effect is as follows:
Problem Solving Scenarios:
I definitely don't want the results to print indefinitely, and then start looking for reasons, mainly because there's no reason to empty the input stream's buffers. So I made some changes to the program code,
#include <iostream> #include <limits>int main () {int ival;while (std::cin >> ival,!std::cin.eof ()) {if (Std::cin.bad ()) Throw Std::runtime_error ("IO stream corrupted"), if (Std::cin.fail ()) {Std::cerr << bad data, try Again "<< std::endl;//fix cin status std::cin.clear (Std::istream::failbit);//std::cin.clear ();//emptying buffer//std:: Cin.sync (); Std::cin.ignore (Std::numeric_limits<std::streamsize>::max (), ' \ n '); std::cout << std:: Cin.fail () << std::endl;continue;}} return 0;}
But this time still can not see the correct result, or infinite printing. Debugging was found because the settings for Failbit did not work. But it works with Cin.clear (). Although I have achieved the results, but why Cin.clear (istream::failbit) has no effect, obviously the book is so written ah. In the mind with all kinds of skeptical attitude to StackOverflow, sure there is a person and I have this problem, the following a person's answer is not how to read, but the general meaning is cin.clear (istream::failbit) can not really reset the state.
http://stackoverflow.com/questions/11246960/resetting-the-state-of-a-stream/11247530#11247530 (Problem address)
The last modified code is as follows:
#include <iostream> #include <limits>int main () {int ival;while (std::cin >> ival,!std::cin.eof ()) {if (Std::cin.bad ()) Throw Std::runtime_error ("IO stream corrupted"), if (Std::cin.fail ()) {Std::cerr << bad data, try Again "<< std::endl;//fix cin Status//method one: Std::cin.clear (~std::istream::failbit & Std::cin.rdstate ());//Method Two:// Std::cin.clear ();//emptying buffer//method One: Std::cin.ignore (Std::numeric_limits<std::streamsize>::max (), ' \ n ');//Method Two:// Std::cin.sync (); std::cout << std::cin.fail () << std::endl;continue;}} return 0;}
C + + Primer (Chinese version Fourth edition) 8th chapter about Cin.clear (Istream::failbit) a misunderstanding