如何立即退出while循环而不跳转到该块的结尾?
例如:
while (choice != 99)
{
cin >> choice;
if (choice == 99)
//Exit here and don't get additional input
cin>>gNum;
}
有什么想法吗?
如何立即退出while循环而不跳转到该块的结尾?
例如:
while (choice != 99)
{
cin >> choice;
if (choice == 99)
//Exit here and don't get additional input
cin>>gNum;
}
有什么想法吗?
使用 break 吗?
while(choice!=99)
{
cin>>choice;
if (choice==99)
break;
cin>>gNum;
}
cin >> choice;
while(choice!=99) {
cin>>gNum;
cin >> choice
}
while(choice!=99)
{
cin>>choice;
if (choice==99)
break; //exit here and don't get additional input
cin>>gNum;
}
这也适用于for循环,并且是结束switch语句的关键字。更多信息在这里。
是的,break命令可以使用。然而,你可能会发现许多程序员在可能的情况下不愿使用它,而是使用条件if语句来执行循环中的其他操作(从而不执行它并干净地退出循环)
像这样的代码将能够实现你所需求的功能,而无需使用break命令。
while(choice!=99) {
cin >> choice;
if (choice != 99) {
cin>>gNum;
}
}
break;
.
while(choice!=99)
{
cin>>choice;
if (choice==99)
break;
cin>>gNum;
}
嗯,break
是什么意思?
while(choice!=99)
{
cin>>choice;
if (choice==99)
exit(0);
cin>>gNum;
}
是的,我很确定你只需放置
break;
正好在你想要退出的地方
就像这样
if (variable == 1)
{
//do something
}
else
{
//exit
break;
}
尝试
break;
你不应该使用break语句来退出循环。 当然,你可以这样做,但并不意味着你应该这样做。 这并不是一个好的编程实践。 更优雅的退出方式如下:
while(choice!=99)
{
cin>>choice;
if (choice==99)
//exit here and don't get additional input
else
cin>>gNum;
}
while(choice != 99) { if(choice == 99) }
- Chris