我想构建一个简单的问卷程序。当我运行代码时,当我只想运行一次并且不重复Cout语句时,它将两次重复该语句。仅当我使用字符串而不是字符时,才会发生。对不起笨拙的写作。[在此处输入图像说明] [1]
代码如下:
#include<iostream>
#include<string>
using namespace std;
bool N='n';
bool Y='y';
bool YES="yes";
bool NO="no";
int main(){
char response, response2, response3;
string response_1, response_2, response_3;
cout<<"Hello would you like to answer a few questions?"<<endl<<"Please input y or n"<<endl;
cin>>response;
{ do{
if((response_1=="yes")||(response=='y')){
cout<<"please continue:"<<endl;
break;}
else if((response_1=="no")||(response=='n')){
cout<<"Please exit the program then:"<<endl;
}
else{
cout<<"Wrong input";
}
}
while((response_1!="yes")||(response!='y'));
}
{ do{
cout<<"Question one"<<endl<<"Can birds sing?.....";/*This statement repeats more than once.*/
cin>>response2;
if((response_2=="yes")||(response2=='y')){
cout<<"Correct they do sing"<<endl;
break;
}
else if((response_2=="no")||(response2=='n')){
cout<<"Do you want to try again?"<<endl;
}
else{
}
}
while((response_2!="yes")||(response2!='y'));
}
{ do{
cout<<"Question two now"<<endl<<"Are pigs smart?......"<<endl;/*This on also repeats moer than once*/
cin>>response3;
if((response_3=="yes")||(response3=='y')){
cout<<"Yes they are smart"<<endl;
break;
}
else if((response_3=="no")||(response3=='n')){
cout<<"Do you want to try again?"<<endl;
}
else{
}
}
while((response_3!="yes")||(response3!='y'));
}
return 0;
}
[1]: https://i.stack.imgur.com/bTnBY.jpg
您将response
声明为char,但第一次试图从控制台初始化它
cin>>response;
您的输入包含3个字符(在您的第三行中"是" [1](,因此response
获取'y',但是" e"one_answers" e"one_answers" s"现在也在输入流中,所以这是原因,为什么在控制台的下一次阅读中:
cin>>response2;
response2
用" e"初始化,这会导致额外的 Can birds sing?.....Question one
打印,然后'reverse 2'get's'并再次打印额外的线。
我建议您删除所有冗余变量,并仅使用STD :: String response
。然后很难犯错。
您可以添加一个变量,该变量计算循环已循环
int loopCount = 0;
int LoopMaxTries = 1;
while ( loopCount < LoopMaxTries /* and possibly other stuff */ ) {
// at the end of the loop
loopCount++;
}