如何停止运行程序?

时间:2019-12-13 19:56:03

标签: c++

我编写了代码,但出现错误。它说:

  

(“ break”语句不在循环或switch语句中)

问题是我在程序中使用循环,但是在此之前,我检查条件是否不正确,我必须打印出“ False”并停止程序,而无需阅读下一个符号。我该怎么做? 这是我的代码:

if(l % 2 == 0) {
    cout << "False";
    break;
}
for(int i = 0; i < 5; i++) {
    cout << '*';
}

2 个答案:

答案 0 :(得分:1)

您只能在breakfor循环或while语句内调用switch

如果这是您的main函数,则main函数完成后,程序将退出。

这可以通过使用return语句来完成(带有返回值,如果程序成功运行,则0是默认的返回值)

if (l%2 == 0) {
    cout << "False";
    return 0;
}

for (int i = 0; i < 5; i++) 
{
    cout << '*';
}

答案 1 :(得分:1)

第一个选项:将不再执行其他代码。

if(l%2==0){
    cout<<"False";
    return 1; //this ends program here
    }
    for(int i=0;i<5;i++){
    cout<<'*';}

或秒

if(l%2==0){
cout<<"False";
}
else{
for(int i=0;i<5;i++){
    cout<<'*';}
}

通过执行else之后的其他代码将被执行,但不会执行此for循环(如果将执行此l%2 == 1代替)

相关问题