如果答案不是y或n,为什么当我尝试运行时,代码不会再次询问用户?
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char answer;
cout << "Do you like cheese?" << endl;
cin >> answer;
if ( answer != 'y' && answer != 'n' ) {
cout << endl << "Wrong answer, Try again: ";
cin >> answer;
}
return 0;
}
我知道它不是循环,但我的其他代码似乎工作正常。如果得分小于0,它将继续要求一个数字。为什么这个代码不会起作用呢?
cout << "Enter the number of goals that were scored: ";
cin >> scored;
if ( scored < 0 ) {
cout << "Error: the number of goals must be greater than 0. Try again: ";
cin >> scored;
}
答案 0 :(得分:0)
在if
声明中更改if
,并将其替换为while
。
while ( answer != 'y' && answer != 'n' ) {
cout << endl << "Wrong answer, Try again: ";
cin >> answer;
}
然后将下面的代码放在下面:
//Do what you want with 'answer' here...
答案 1 :(得分:-1)
#include <iostream>
using namespace std;
int main(){
char answer;
cout<<"do you like cheese?"<<endl;
cin>>answer;
while((answer!='y'&&answer!='n')){
cout<<"do you like cheese?"<<endl;
cin>>answer;
}
return 0;
}