我在执行以下代码时遇到了一些问题。我在 Xcode (OS X) 中使用它。
for ( unsigned char i = 0; i < 5; i++ ) {
int value;
std::cout << ">> Enter \"value\": ";
std::cin >> value;
if ( std::cin.fail() ) { std::cout << "Error: It's not integer value!\n"; } else { std::cout << "The value format is ok!\n"; }
std::cout << "value = " << value << std::endl;
}
这里我只是循环输入了 5 个值。每次我检查它是否出错。当我设置错误的值(“asdf”)时,std::cin 变得疯狂并且不再工作。看这个:
>> Enter "value": 90
The value format is ok!
value = 90
>> Enter "value": 2343
The value format is ok!
value = 2343
>> Enter "value": 34
The value format is ok!
value = 34
>> Enter "value": asdf
Error: It's not integer value!
value = 0
>> Enter "value": Error: It's not integer value!
value = 0
80
32423
adf
3843
asdf
asdf
23423
如何输入reset std::cin?我尝试输入其他值,但我不能,因为 std::cin 在输入错误值后似乎不再起作用。
最佳答案
当条件 std::cin.fail()
发生时,您可以使用:
std::cin.clear();
std::cin.ignore();
然后使用 continue;
语句继续循环。 std::cin.clear()
清除错误标志并设置新的,std::cin.ignore()
有效地忽略它们(通过提取和丢弃它们).
来源:
关于c++ - 使用时如何重置 std::cin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39282953/