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

How internally string/char is stored in int and float

本文关键字:int float 存储 字符串 字符 内部      更新时间:2023-10-16

我在执行以下代码块时错误找到了场景

#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++,如果我在此过程中错过了任何参考资料,请指出我。

int input1;
float input2;

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

std::cin期望输入一个整数,但您输入了'a',这使得std::cinfail。该故障持续存在,因此在清除failbit之前,无法对std::cin执行任何提取操作。

输入操作失败后,input1input2仍然是"未定义的"。打印它们会导致未定义的行为。

当流无法解释为适当类型的有效值时,提取运算符不会更改变量。因此,您会看到input1input2的未初始化值。您可以在cin上检查failbit以查看提取运算符是否成功。

例如:

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