如果我决定输入 (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)

本文关键字:如果 输入 输出 出错 工作 我的 决定 为什么      更新时间:2023-10-16

所以对于我的代码,它要求用户输入一个数字来表示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;读取并删除12保留在流中。cin仅在流为空时才阻止。