Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 什么';cin和gt之间的区别是什么&燃气轮机;x;cin>&燃气轮机;y和cin>&燃气轮机;x>&燃气轮机;Y_C++ - Fatal编程技术网

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从流中读取
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