【问题标题】:while loop continues after sentinel value is reached达到标记值后,while循环继续
【发布时间】: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


【解决方案1】:

在 switch case 中的 break 语句只退出 switch 块,而不是外部 while 循环。您的代码将继续运行,直到下一次评估 while 循环条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-21
    • 2017-11-21
    • 2014-03-11
    • 2013-01-10
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多