【发布时间】:2016-03-14 13:06:32
【问题描述】:
我有一个简单的代码:如果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;
}
【问题讨论】: