为什么字符串在C++中变成整数?

Pom*_*ite 2 c++

#include <iostream>
using namespace std;
int main () {
    int N;
    cout << " Input an integer:";
    cin >> N;
    cout << " The integer entered is:" << N << endl;        
}
Run Code Online (Sandbox Code Playgroud)

当我输入一个Integer时它会返回相同的值,但是当我输入hello它时它会给我1961729588.

Bor*_*der 13

该字符串不成为一个整数,该std::cin操作将失败,你会得到作为输出的是,这是在垃圾值N最初.初始化N为0,并输入"hello",您应该看到0作为输出.

  • 或者,只是为了使行为更清晰,将"N"初始化为"42"或"123456". (3认同)
  • @πάνταῥεῖ不,这是对C++ 11的改变[请参阅我的问题](http://stackoverflow.com/questions/19522504/istream-behavior-change-in-c-upon-failure). (2认同)

πάν*_*ῥεῖ 5

"当我输入一个Integer时,它会返回相同的值,但是当我输入hello它时,它会给我1961729588?."

当给定的输入无法转换为整数时,cin >> N;实际上无法返回false流状态.你可以检查这样的错误情况

 if(!(cin >> N)) {
     cerr << "Input a valid number!" << endl;
 }
 else {
     cout << " The integer entered is:" << N << endl;
 }
Run Code Online (Sandbox Code Playgroud)

将值N初始化(重置)为int()(默认值)实际呈现的值0.


完整的现场样本

#include <iostream>
using namespace std;
int main () {
    int N;
    cout << " Input an integer:";
    if(!(cin >> N)) {
        cout << "Input a valid number!" << endl;
        cout << "N = " << N << endl;
    }
    else {
        cout << " The integer entered is:" << N << endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输入

Hello
Run Code Online (Sandbox Code Playgroud)

产量

Input an integer:Input a valid number!
N = 0
Run Code Online (Sandbox Code Playgroud)

使用Ideone代码示例交叉检查

我无法重现得到一些垃圾值一样1961729588.std::istream& operator>>(std::istream&, int&);输入运算符正确地重置了该值.


这是您当前编译器的实现,c ++标准level(-std=c++11)设置的问题吗?

我在cppreference.com上找到了关于c ++标准的最终差异的一些注释:

在此输入图像描述

在此输入图像描述

虽然我没有发现他们真正提到的"上述价值",但说实话.