内部字符串/ char如何存储在int和float中

时间:2017-03-04 18:30:22

标签: c++

我执行以下代码块时 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

有人可以解释一下上述场景的内部处理方式,导致上述情况吗?

注意 -

  • 在VS2015中运行上述内容。

我正在尝试使用C ++,如果我错过了这个过程,请指出任何参考。

2 个答案:

答案 0 :(得分:4)

int input1;
float input2;

此时,input1input2都有未定义的值,因为您没有初始化它们。

std::cin期待输入一个整数,但您输入'a'std::cinfail。该故障仍然存在,因此在std::cin被清除之前,failbit不能执行任何提取操作。

输入操作失败后,input1input2仍未定义&#34;。打印它们会导致未定义的行为。

答案 1 :(得分:2)

当流不能被解释为适当类型的有效值时,提取运算符不会更改变量。因此,您会看到input1input2的未初始化值。您可以查看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');
    }