C++ 什么';cin和gt之间的区别是什么&燃气轮机;x;cin>&燃气轮机;y和cin>&燃气轮机;x>&燃气轮机;Y
我写了一个小程序。代码如下:C++ 什么';cin和gt之间的区别是什么&燃气轮机;x;cin>&燃气轮机;y和cin>&燃气轮机;x>&燃气轮机;Y,c++,C++,我写了一个小程序。代码如下: #include<iostream> using namespace std; int main() { int x; float y; cout<<"Please input an int number:"<<endl; cin>>x; cout<<"The input number is x= "<<endl; cout<<"Please input a
#include<iostream>
using namespace std;
int main()
{
int x;
float y;
cout<<"Please input an int number:"<<endl;
cin>>x;
cout<<"The input number is x= "<<endl;
cout<<"Please input a float number:"<<endl;
cin>>y;
cout<<"The float number is y= "<<endl;
return 0;
}
我以为它会把69.8转换成69,然后让我输入下一个数字y,但它会自动输入,为什么?这是因为程序需要一个
int
,而你给它一个双精度
。然后,可以转换为int
的所有字符都将被转换,但不能转换的字符将保留在缓冲区中。在下一次调用std::cin
时,程序将读取缓冲区中剩余的内容,这就是为什么y
被自动设置的原因
读取此代码,以了解如何处理C++中的错误类型输入并清除该缓冲区。p> 首先,
cin>>x代码>读取编号69
以及所有内容。这是正确的整数。其他字符保留在缓冲区中
第二,cin>>y
尝试从流中读取并获取.8
,它也会更正浮点数。C++流(如std::cin
),在读取int
时,在任何不属于整数值的字符处停止。它包括一个“.
字符
读取int
时,没有读取浮点值或将浮点值转换为int
的中间步骤。int
是直接读取的,因此,如果在一个数字之后有任何非数字,则读取将停止,并且非数字将保留在流中,由下一个操作读取
第一个cin>>x因此,code>从流中读取69
,并将”留在等待读取的位置。
。cin>>y
遇到'。
将其视为浮点值的一部分,然后继续。因此,y
接收值0.8
主题行与所问问题无关。可能重复
Please input an int number:
69.8
The int number is x= 69
The float number is y= 0.8