c++ - 为什么这段代码以无限循环结束,从 std::cin 读取

标签 c++ loops stdvector

您好,我尝试通过 vector 为我的函数创建一个输入函数。

但是,我不知道为什么我的输入会变成死循环?

do {            
    cout << "Please enter the next number: ";
    cin >> num;
    number.push_back(num);
    cout << "Do you want to end? enter 0 to continue.";
    dec = NULL;
    cin >> dec;
} while(dec == 0);

最佳答案

"I don't know why my input become infinite loop."

我能想到的唯一原因是,任何不正确的输入集 cinfail状态。在这种情况下(例如,输入了无效数字,或者只是按下了 ENTER)cin设置为 faildec 中陈述和你的值(value)永远不会改变。一次cinfail state 任何后续的输入操作都将分别失败,并且输入的主题不会改变。

为了防止这种行为,你必须clear() std::istream的状态,并在继续之前阅读到安全点(另请参阅:How to test whether stringstream operator>> has parsed a bad type and skip it):

do {
    cout << "Please enter the next number: ";
    if(cin >> num) {
        number.push_back(num);
    }
    else {
       cerr << "Invalid input, enter a number please." << std::endl;
       std::string dummy;  
       cin.clear();
       cin >> dummy;
    }
    cout << "Do you want to end? enter 0 to continue.";
    dec = -1;
    if(!(cin >> dec)) {
       std::string dummy;  
       cin.clear();
       cin >> dummy;
       break; // Escape from the loop if anything other than 0 was
              // typed in
    }
} while(dec == 0);

这是三个工作演示,使用不同的输入来结束循环:

1st Input :

1
0
2
0
3
0
4

进入

2nd Input :

1
0
2
0
3
0
4
xyz

3rd Input

1
0
2
0
3
0
4
42

循环是有限的,以上所有的输出都是

1234

<子> 您还应该注意到我已经更改了 bool dec;int dec; ,但这可能是次要的一点。

关于c++ - 为什么这段代码以无限循环结束,从 std::cin 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29633122/

相关文章:

C++ vector remove_if 对

javascript - 如何使用js遍历特定属性?

linux - 意外标记附近的语法错误 "do"

Jquery Loop 附加图像元素仅附加一次

c++ - 将表示二维数组的 std::vector<std::vector <double>> 转换为 cv::Mat

c++ - 在插入 vector C++之前验证用户输入

c++ - 使用 MINGW32 在 Debian 上用 C++ 和 MySQL 编译

c++ - 字典可以在c++中使用吗

c++ 项目,vs2010, "build failed"没有错误

c++ - 循环 vector - 寻找最小可能的 'cost' (来自 CodeChef)