c++ - 使用时如何重置 std::cin?

标签 c++ std cin

我在执行以下代码时遇到了一些问题。我在 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() 有效地忽略它们(通过提取和丢弃它们).

来源:

  1. cin.ignore()
  2. cin.clear()

关于c++ - 使用时如何重置 std::cin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39282953/

相关文章:

c++ - char 指针,使用 cin.getline 读取?

c++ - MSVS 2015 : vector<bool> has no 'data' member

c++ - 如何在一个 vector 中存储具有不同数据类型的对象

java - 如何编译支持GPU的tflite?

c++ - 处理空格字符作为输入

c++ - std::cin >> std::string 是如何实现的?

c++ - 由于架构 x86_64 的符号未定义,GLFW 的最小示例失败

c++ - 获取错误 'char16_t and char32_t undeclared'

c++ - 使用嵌套的 std 和 posix 命名空间是否未定义?

c++ - Visual 2015 上的 std::get_time 不会在不正确的日期失败