【发布时间】:2017-02-14 00:43:13
【问题描述】:
我目前对 while 循环感到困惑,特别是为什么循环仍然运行循环中的所有其他内容,特别是在达到哨兵值之后...
下面是我的代码示例:
while (quit != -1) {
cout<<"Options: a)ir; w)ater; s)teel; q)uit \n";
char option=' ';
cin>>option;
option = toupper(option);
while( option != 'A' && option != 'W' && option != 'S' && option != 'Q'){
cin.clear();
cout<<"INVALID INPUT!! \n";
cin>>option;
option = toupper(option);
}
switch(option){
case 'Q':
cout<<"You Have Quit!";
quit = -1;
break;
}
cout<<"Please input the distance: \n";
double distance=0;
cin>>distance;
while(distance < 0){
cin.clear();
cout<<"INVALID INPUT \n";
cin>>distance;
}
switch(option){
case 'A':
seconds = distance/speed_a;
cout<< "Time travled: " << setprecision(2) << fixed << seconds << "\n";
break;
case 'W':
seconds = distance/speed_w;
cout<< "Time travled: " << setprecision(2) << fixed << seconds << "\n";
break;
case 'S':
seconds = distance/speed_s;
cout<< "Time travled: " << setprecision(2) << fixed << seconds << "\n";
break;
}
}
基本上当用户输入 'q' 字符时,它会运行退出 switch 语句......它确实退出了循环,但它仍然要求在结束循环之前行进的距离......
输出如下:
Options: a)ir; w)ater; s)teel; q)uit
q
You Have Quit!
Please input the distance:
0
--------------------------------
Process exited after 2.944 seconds with return value 0
Press any key to continue . . .
有什么方法可以编辑代码,让它立即退出循环,或者这只是所有循环的预编程方式?
任何建议将不胜感激
【问题讨论】:
-
switch 内部的 break 只会中断 switch,而不是 while 循环。您应该使用 if 来测试选项或在 switch 块之后测试退出。
标签: c++11 while-loop sentinel