我想构建一个简单的问卷调查程序。当我运行代码时,如果我只希望运行一次而不重复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
答案 0 :(得分:1)
您将response
声明为字符,但这是您首次尝试从控制台对其进行初始化时
cin>>response;
您的输入包含3个字符(示例[1]第三行中的“是”),因此response
得到'y',但是'e'和's'现在也在输入流中,所以这就是为什么在下一次从控制台读取时的原因:
cin>>response2;
response2
用'e'初始化,这会导致打印额外的Can birds sing?.....Question one
,然后'response2'得到's'并再次打印多余的行。
我建议您删除所有冗余变量,并仅使用std :: string response
。那样会容易出错。
答案 1 :(得分:1)
您可以添加一个变量,该变量计算循环循环的次数
+--------------+----------------+-----------+
| usps_primary | usps_preferred | variation |
+--------------+----------------+-----------+
| ALLEY | ALY | ALLEY |
| ALLEY | ALY | ALLEE |
| ALLEY | ALY | ALLY |
| ALLEY | ALY | ALY |
| ANEX | ANX | ANX |
| ANEX | ANX | ANNX |
| ANEX | ANX | ANEX |
| ANEX | ANX | ANNEX |
| East | E | E |
| East | E | East |
| North | N | North |
| North | N | N |
| South | S | South |
| South | S | S |
| West | W | W |
| West | W | West |
+--------------+----------------+-----------+