如果我决定输入 (1 2) 而它要求 x,为什么我的输出会出错,但如果我输入 (12) 工作正常
Why does my output go faulty if i decide to input (1 2) while its asking for the x but works fine if i input(12)
所以对于我的代码,它要求用户输入一个数字来表示x,但我碰巧用手指输入了它,我输入了(1 2(在1和2之间有一个空格,我的代码直接用于输出我的x和y甚至认为它还没有要求y坐标。
#include <iostream>
using namespace std;
int main(){
double x, y;
cout << "Enter x coordinate: ";
cin >> x;
while (!cin.good() ) {
cout << "Invalid input" << endl;
cin.clear();
cin.ignore(INT_MAX, 'n');
cout << "Enter your x coordinate";
cin >> x;
}
cout << "Enter y coordinate: ";
cin >> y;
while(!cin.good()){
cout << "Invalid input" << endl;
cin.clear();
cin.ignore(INT_MAX, 'n');
cout << "Enter your y coordinate";
cin >> y;
}
cout << "You x coordinate is at: " << x << ", Your y coordinate is at: " << y ;
return 0;
}
使用cin
,您可以通过输入数据并按回车键或空格分隔来获得输入,因此:
cin >> var;
cin >> var2;
可以通过输入 var1 的数据并按 Enter 然后输入 var2 的数据并按 Enter 或通过输入 var1 和 var2 的数据来获取输入eather用空格分隔,如果数据有效,它将接受它。
请注意,当它!cin.good()
数据时,它将再次启动cin
您将1 2
写入流中。cin >> x;
读取并删除1
。2
保留在流中。cin
仅在流为空时才阻止。
相关文章:
- std::unordered_map 如果输入大小已知,如何优化批量插入
- 如果输入类型与目标类型不同,"cin"变量是否重置为某个默认值?
- 如果输入缓冲区不为空,请使用getchar.()检测Ctrl+d
- 如果输入数字为负数,如何循环
- 如果输入变量的数据类型与以前不同,如何使我的循环仍然正常运行?
- 一个倒梯形,但如果输入高度对于宽度来说太大,那么它应该报告,不可能("不可能的形状"是什么)
- C++ 在 CIN 双精度时挂起,但如果输入整数,则继续
- 用户输入逻辑运算符符号或数字,如果输入字符或字符串则无效
- 如果输入为 NULL,则返回 -1
- 如果输入图像矩阵实际上是复杂类型,MATLAB imresize() 会怎么做?
- 二项式系数程序输出错误的结果,如果输入是大的(C++)
- 如果输入数未知,则接受输入
- 如果输入不是整数,则连续提示用户输入
- C++:如果输入不是整数,为什么这段代码会运行一个无休止的循环
- 如果输入大于零,是否有一行用于从输入中减去 1
- 如果输入没有双精度,则停止输入
- 如果输入流无效会发生什么
- switch语句:如果输入不是数字(1到9)或字母(a到z)输出<<“错误”?C++
- 如果输入在 c++ 中无效,如何重复输入命令
- 如果输入了非整数,如何防止无限循环