是否有一种方法可以在运行时停止循环重复一次不止一次
Is there a way to stop the loop repeating more than once when running
我想构建一个简单的问卷程序。当我运行代码时,当我只想运行一次并且不重复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"answers" e"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++;
}
相关文章:
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- (C++)虽然循环一次不起作用,但我引入了多个变量
- 花括号使循环运行一次?
- 从子菜单返回后,正确的输入至少进入验证循环一次
- foor 循环的最后一次迭代中的指针更改
- 有没有办法在循环中的条件至少满足一次时运行语句?
- 循环中本地对象的析构函数是否保证在下一次迭代之前被调用?
- For循环在cpp中仅执行一次
- 将一副牌循环100次(一副牌)
- 如何强制循环执行另一次迭代到零并关闭循环
- (C++)for循环中的空初始语句是否保存所有编译器中变量的上一次初始化
- 当使用文件中的getline时,循环仅循环一次
- Arduino循环一次
- 在一个文件中循环一次,将行读取到添加到数组中的对象中
- 程序只循环一次
- 每 10 秒循环一次
- 每 'x' ms 重复循环一次
- 为什么这个单词排序程序只循环一次?
- 如何在c++中循环一次要求输入的switch-case语句?
- 通过只循环一次来组合c++标准算法