std :: cin对意外输入的行为

时间:2016-03-03 01:00:18

标签: c++

我想在给出意外输入时测试std::cin的行为。为什么std::cin以非确定的方式返回0和2.07386e-317?

#include <iostream>

using namespace std;

int main(){
    double foo, bar;
    while(cin.good() and cin >> foo >> bar){    
        cout << foo << " " << bar << endl;
    }
    if (cin.eof()){
            cout << "Ooops, EOF encountered.\n";
    }
    else{
        cout << "Something weird happened!\n";
        cout << foo << " " << bar << endl;
    }
    return 0;
}

每当我输入时,

 <a_number> <non-number>

输出为<a_number> 0

每当我输入时,

<non-number> <anything>

输出为0 2.07386e-317

我通过将输入数量增加到3和

来尝试确切的代码
<non-number> <non-number> <non-number>

输出为0 0 2.07353e-317

对于4个输入,

`<non-number> <non-number> <non-number> <non-number>`

输出为0 2.07353e-317 0 2.07353e-317

最后,对于5个输入,

`<non-number> <non-number> <non-number> <non-number> <non-number>`

输出为0 2.07353e-317 2.07353e-317 0 2.07353e-317

我查看the November 2014 working draft of current standart (C++14)并且在第27.4.2节中看不到任何有用的信息,其中窄流对象的解释方式非常简短。我希望看到std::cin的内部工作细节。我错过了什么吗?

我很好奇行为的原因。感谢帮助。

1 个答案:

答案 0 :(得分:2)

你不应该试图在“发生奇怪的事情”的情况下打印变量,因为这意味着变量提取不成功。从第一个错误输入开始的任何变量都不会被分配。

请参阅How to test whether stringstream operator>> has parsed a bad type and skip it了解如何跳过错误输入。

相关问题