C++中用cin.fail()来判断当前的输入和预期是否相同,如果不同的话cin.fail()返回true。如果我现在想获取使得cin.fail()为true的那个输入值,我要怎么获取?
先看代码:
#include <iostream> int main( void ) { int number; char c; while(1) { std::cin >> number; if ( std::cin.fail() ) { std::cin.clear(); std::cin >> c; std::cout << "fail,the input char is:" << c << std::endl; std::cout << "and now number is :" << number << std::endl; } else { std::cout << "Your input is:" << number << std::endl; } } return 0; }
步骤就是:
- 先用
std::cin.clear()
清除fail
状态 - 用一个更通用的类型去读取,通常是
char
具体原因,你应该懂吧
总之,一句N多教科书强调N多次的话:
当输入流读取失败时,它会把字符放回原处,等待下次读取
这句话也有个例外就是某些场合下的 换行符
还是不懂,看SO
上这个:
http://stackoverflow.com/questions/20...
和:
http://web.eecs.utk.edu/~cs102/lectur...