简体   繁体   English

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

[英]Behavior of std::cin for unexpected inputs

I wanted to test behavior of std::cin when an unexpected input is given. 当给出意外输入时,我想测试std::cin行为。 Why does std::cin return 0 and 2.07386e-317 in a non-deterministic way? 为什么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;
}

Whenever I type, 每当我输入

 <a_number> <non-number>

Output is <a_number> 0 输出为<a_number> 0

And whenever I type, 每当我打字时

<non-number> <anything>

Output is 0 2.07386e-317 输出为0 2.07386e-317


I tried exact code by increasing number of input to 3 and, 我通过将输入数量增加到3来尝试了确切的代码,

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

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


For 4 inputs, 对于4个输入,

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

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


Lastly, for 5 inputs, 最后,对于5个输入,

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

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

I looked at the November 2014 working draft of current standart (C++14) and couldn't see any helpful information on this at § 27.4.2 where Narrow stream objects are explained in a surprisingly short way. 我查看了当前标准(C ++ 14)的2014年11月工作草案,在§27.4.2上看不到任何有用的信息,在该文章中以狭窄的方式解释了窄流对象。 I expected to see internal working details of std::cin . 我希望看到std::cin内部工作细节。 Am I missing something? 我想念什么吗?

I am curious about the reasons of behavior. 我对行为的原因感到好奇。 Appreciate the help. 感谢帮助。

You shouldn't try to print the variables in the "Something weird happened" case, because that means the variable extraction wasn't successful. 在“发生某些奇怪的情况”的情况下,您不应尝试打印变量,因为这意味着变量提取不成功。 Any of the variables starting from the first incorrect input will not have been assigned. 从第一个错误输入开始的任何变量都不会被分配。

See How to test whether stringstream operator>> has parsed a bad type and skip it for how you can skip over bad inputs. 有关如何跳过错误输入的信息,请参见如何测试stringstream运算符>>是否已解析错误类型并跳过它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM