在达到哨兵值后继续循环

时间:2017-02-14 00:43:14

标签: c++11 while-loop sentinel

我目前对while循环感到困惑,特别是为什么在达到sentinel值之后循环仍然在循环中运行其他所有内容...

这是我的代码示例:

retrbinary

基本上当用户输入' q'它运行退出开关语句...它确实退出循环但它仍然要求在结束循环之前行进的距离..

输出如下所示:

    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;
    }
}

有没有办法编辑代码,所以它立即退出循环或者这是所有循环预编程的方式?

任何建议都将不胜感激

1 个答案:

答案 0 :(得分:1)

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