使用时如何重设std :: cin? [英] How to reset std::cin when using it?

查看:80
本文介绍了使用时如何重设std :: cin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some problem with following code. I use it in Xcode (OS X).

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

[removed my first try of that code]

如何输入重置std :: cin吗?我尝试输入其他值,但因为输入错误的值后std :: cin似乎不再起作用。

How to input reset std::cin? I try to input another values but I can't because std::cin seems to not work anymore after my wrong value.

UPD2
在第二次尝试中,我使用以下代码:

UPD2 In my second try I use this code:

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;

}

在这里,我仅循环输入5个值。每次我检查错误时。当我设置了错误的值( asdf)std :: cin会发疯,并且不再起作用。我得到以下输出:

Here I just input 5 values in a loop. Everytime I check it on error. When I set the wrong value ("asdf") std::cin goes crazy and doesn't work anymore. I get this output:

>> 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


推荐答案

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

std::cin.clear();
std::cin.ignore();

然后继续循环,并继续; 语句。 std :: cin.clear()清除错误标志,并设置新的错误标志,以及 std :: cin.ignore()有效地忽略了它们(通过提取和丢弃它们)。

And then continue with the loop, with a continue; statement. std::cin.clear() clears the error flags, and sets new ones, and std::cin.ignore() effectively ignores them (by extracting and discarding them).

来源:


  1. cin.ignore()

  2. cin.clear()

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

这篇关于使用时如何重设std :: cin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆