我执行以下代码块时 MISTAKENLY 找到了该方案
#include <iostream>
using namespace std;
int main()
{
int input1;
float input2;
cout << "Enter a real number :";
cin >> input1;
cout << "The int number is " << input1 << endl;
cout << "Enter another number :";
cin >> input2;
cout << "The float number is " << input2 << endl;
}
以上的输出是
Enter a real number :a
The int number is -858993460
Enter another number :a
The float number is -1.07374e+08
有人可以解释一下上述场景的内部处理方式,导致上述情况吗?
注意 -
我正在尝试使用C ++,如果我错过了这个过程,请指出任何参考。
答案 0 :(得分:4)
int input1;
float input2;
此时,input1
和input2
都有未定义的值,因为您没有初始化它们。
std::cin
期待输入一个整数,但您输入'a'
,std::cin
为fail
。该故障仍然存在,因此在std::cin
被清除之前,failbit
不能执行任何提取操作。
输入操作失败后,input1
和input2
仍未定义&#34;。打印它们会导致未定义的行为。
答案 1 :(得分:2)
当流不能被解释为适当类型的有效值时,提取运算符不会更改变量。因此,您会看到input1
和input2
的未初始化值。您可以查看failbit
上的cin
,了解提取运算符是否成功。
例如:
int input1;
cout << "Enter a real number :";
cin >> input1;
if(cin.good())
{
cout << "The int number is " << input1 << endl;
}
else
{
cout << "The input was not a number." << endl;
// skip to the end of the input
cin.clear();
cin.ignore(INT_MAX, '\n');
}