我有一个简单的代码:如果ch
为Y
,则第一个if
语句运行,如果为N
,则运行另一个else
语句,如果还有其他内容,则运行该语句。但是,如果我给出多个字符,那么它将多次写出“错误的输入”。我该如何解决这个问题,所以我编写的else
语句只能运行一次?
#include <iostream>
using namespace std;
int main()
{
bool running = true;
char ch;
do{
cout << "Enter Y or N: ";
cin >> ch;
cout << endl;
if(ch == 'Y'){
cout << "You entered yes." << endl;
running = false;
} else if(ch == 'N'){
cout << "You entered no." << endl;
running = false;
} else{
cout << "Wrong input." << endl;
}
}while(running);
return 0;
}
您需要做的是清除输入流的其余部分,以确保在下一次迭代时,您正在等待新输入,而不是读取缓冲区中剩余的输入。我们可以使用ignore
像
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
您可以将其放置在do循环的最后一行,以便为每种情况清除缓冲区,也可以将其添加到最后的else语句。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句