内部字符串/字符如何在 int 和 float 中存储
How internally string/char is stored in int and float
我在执行以下代码块时错误地找到了场景
#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;
此时,input1
和input2
都具有未定义的值,因为您没有初始化它们。
std::cin
期望输入一个整数,但您输入了'a'
,这使得std::cin
fail
。该故障持续存在,因此在清除failbit
之前,无法对std::cin
执行任何提取操作。
输入操作失败后,input1
和input2
仍然是"未定义的"。打印它们会导致未定义的行为。
当流无法解释为适当类型的有效值时,提取运算符不会更改变量。因此,您会看到input1
和input2
的未初始化值。您可以在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');
}
相关文章:
- 没有从阵列<float>到阵列<int>的可行转换
- 为什么我会收到此错误?无法将 {lb, ub} 从<大括号括起来的初始值设定项列表>转换为 float(**)(float*, int)
- 如何将 qml 的文本转换为 float 和 int
- 有没有比static_cast更优雅的从int到float的演员阵容<float>?
- 如何在函数中将字符串和分数存储为(Int 或 float)
- 谷歌测试编译错误 Os X:函数式转换从"int"到"internal::FloatingEq2Matcher"的模糊转换<float>
- 如何使用 std:from_chars 在 C++17 中从字符串转换为 int/float
- 如何修复 E2015 "ambiguity between pow(double,double) and pow(float,int)"
- C++优化从 int 到 float 的数组转换
- 如何在 c++ 中将数据从文件读取到 int/float 值
- 错误:二进制'operator*' 'int [1]'和'float'类型的操作数无效
- 功能使用INT和Float类型作为C 中的参数过载
- 内部字符串/字符如何在 int 和 float 中存储
- 无法将'int*'转换为参数'1'的'float*'
- 将 python list 作为 'float*' 或 'int*' 传递给 C/C++
- 在C++/Visual Studio中,通过给定数据格式(doubles、float、int、1位bools)的UDP发
- 当float转换为int时,此代码中是如何/为什么进行缩小的
- C++ 将字符串转换为 16 位无符号/有符号的 int/float
- C++:int*/float*到char*,为什么使用repret_cast会得到不同的结果
- 如何在等待用户输入int, float或其他类型时拒绝输入char/string