如何在使用时重置std :: cin?

Jav*_*ner 2 c++ std cin

我有以下代码的问题.我在Xcode(OS X)中使用它.

[删除了我对该代码的第一次尝试]

如何输入reset std :: cin?我尝试输入另一个值,但我不能,因为std :: cin似乎在我错误的值之后不再工作了.

UPD2 在我的第二次尝试中,我使用此代码:

for ( unsigned char i = 0; i < 5; i++ ) {

    int value = 0;

    std::cout << "\n>> Enter \"value\": ";
    std::cin >> value;

    if ( std::cin.fail() ) {
        std::cin.clear();
        std::cin.ignore();
        std::cout << "Error: It's not integer value!\n";
    } else {
        std::cout << "The value format is ok!\n";
    }

    std::cout << "value = " << value << std::endl;

}
Run Code Online (Sandbox Code Playgroud)

这里我只是在一个循环中输入5个值.每次我检查错误.当我设置错误的值("asdf")时,std :: cin变得疯狂并且不再起作用.我得到这个输出:

>> Enter "value": 4
The value format is ok!
value = 4

>> Enter "value": 234
The value format is ok!
value = 234

>> Enter "value": asdfghjkl
Error: It's not integer value!
value = 0

>> Enter "value": Error: It's not integer value!
value = 0

>> Enter "value": Error: It's not integer value!
value = 0
234
234
78
345
657
345
dsf
f
Run Code Online (Sandbox Code Playgroud)

Arn*_*rah 5

当条件std::cin.fail()发生时,您可以使用:

std::cin.clear();
std::cin.ignore();
Run Code Online (Sandbox Code Playgroud)

然后继续循环,并continue;发表声明.std::cin.clear()清除错误标志,并设置新标志,并std::cin.ignore()有效地忽略它们(通过提取和丢弃它们).

资料来源:

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

  • `clear`清除流的错误状态标志.它对角色没有任何作用.并且`ignore`没有任何参数只会丢弃一个字符,这意味着如果你输入`"asdf"`,它将循环4次,告诉你输入是坏的,然后它再次输入.你应该把`std :: cin :: ignore(std :: numeric_limits <std :: streamsize> :: max(),'\n')`丢弃到行尾. (4认同)
  • 谢谢你指出那些@BenjaminLindley我没有意识到.我在很大程度上依赖于文档,并没有仔细阅读它们.我的错 (2认同)