为什么将 char 'g' 读入 int 会在此代码中产生数字 -858993460?
Why does reading char 'g' into an int produce the number -858993460 in this code?
我正在做一个 class 的练习,我决定看看如果在代码期望 int
时输入 char
会发生什么。我输入字母 'g'
只是为了看看会发生什么......它输出 -858993460
我不知道为什么。
代码如下:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int test;
cout << "Please enter a even integer or a odd integer. " << endl;
cin >> test;
cout << test; //here is where i got the -858993460
if (test % 2)
{cout << "TRIANGLE" << endl;}
else
{cout << "SQUARE" << endl;}
return 0;
}
那么 -858993460
从何而来?
如果您检查读取的结果,您会发现没有读取任何内容。
if (cin >> test) {
cout << "read " << test << endl;
}
else {
cout << "read failed" << endl;
}
您正在打印的值是 test
的未初始化值。它可以从 运行 运行 变化。从技术上讲,打印它是未定义的行为,因此您的程序甚至可能崩溃,尽管这在实践中不太可能发生。
std::basic_istream::operator>> 的行为从 C++11 开始改变。在 C++11 之前,
If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.
好像是这样的。 test
未初始化;然后你打印出一个随机值。请注意,这实际上是未定义的行为。
从 C++11 开始,
If extraction fails, zero is written to value and failbit is set.
这意味着您将在 C++11 之后获得值 0
。
我正在做一个 class 的练习,我决定看看如果在代码期望 int
时输入 char
会发生什么。我输入字母 'g'
只是为了看看会发生什么......它输出 -858993460
我不知道为什么。
代码如下:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int test;
cout << "Please enter a even integer or a odd integer. " << endl;
cin >> test;
cout << test; //here is where i got the -858993460
if (test % 2)
{cout << "TRIANGLE" << endl;}
else
{cout << "SQUARE" << endl;}
return 0;
}
那么 -858993460
从何而来?
如果您检查读取的结果,您会发现没有读取任何内容。
if (cin >> test) {
cout << "read " << test << endl;
}
else {
cout << "read failed" << endl;
}
您正在打印的值是 test
的未初始化值。它可以从 运行 运行 变化。从技术上讲,打印它是未定义的行为,因此您的程序甚至可能崩溃,尽管这在实践中不太可能发生。
std::basic_istream::operator>> 的行为从 C++11 开始改变。在 C++11 之前,
If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.
好像是这样的。 test
未初始化;然后你打印出一个随机值。请注意,这实际上是未定义的行为。
从 C++11 开始,
If extraction fails, zero is written to value and failbit is set.
这意味着您将在 C++11 之后获得值 0
。