简体   繁体   English

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

[英]How internally string/char is stored in int and float

I have MISTAKENLY found the scenario while executing the following block of code 在执行以下代码块时,我错误地找到了方案

#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;
}

The output for the above is 上面的输出是

Enter a real number :a
The int number is -858993460
Enter another number :a
The float number is -1.07374e+08

Can anyone kindly explain how internally the above scenario is getting handled resulting in the above scenario ? 谁能解释一下上述情况是如何在内部处理的?

Note - 注意 -

  • Running the above in VS2015. 在VS2015中运行以上内容。

As i am newly experimenting with C++, please point me to any reference if i have missed in the process. 当我刚开始尝试C ++时,如果我在过程中错过了任何内容,请给我指出任何参考。

int input1;
float input2;

At this point, both input1 and input2 have undefined values since you didn't initialize them. 此时, input1input2都具有未定义的值,因为您尚未初始化它们。

std::cin was expecting an integer to be entered but you entered 'a' , which made std::cin to fail . std::cin期望输入整数,但是您输入了'a' ,这使std::cin fail That failure persists such that no extraction operation can be performed with std::cin until the failbit is cleared. 这仍然失败,使得没有提取操作可以被执行std::cin直到failbit被清除。

After your failed input operations, input1 and input2 are still "undefined". 输入操作失败后, input1input2仍为“未定义”。 Printing them lead to Undefined Behavior. 打印它们会导致未定义的行为。

The extraction operator does not change the variables when the stream cannot be interpreted as a valid value of the appropriate type. 当流无法解释为适当类型的有效值时,提取运算符不会更改变量。 Therefore you see uninitialized values for input1 and input2 . 因此,您会看到input1input2未初始化值。 You can check the failbit on cin to see whether the extraction operator was successful. 您可以在cin上检查failbit ,以查看提取运算符是否成功。

For example: 例如:

    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');
    }

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

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