为什么在输入标记值后我的C ++标记循环会继续?

时间:2016-10-09 22:42:43

标签: c++ loops sentinel

当我输入字符串“NOMORE”时,它会继续到下一行,它会询问我的车速。它只在完成for循环时停止循环。我怎样才能使它在输入“NOMORE”时立即停止?谢谢你的帮助。我真的很感激。如果我做的话,抱歉浪费你的时间:(

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

int main()
{
    string plate;
    int totalCount;
    int ticketCount = 0;
    double speed;
    double base = 150;
    double limit;
    double ticket;
    double overspeed;

    for (totalCount = 0; plate != "NOMORE"; totalCount++)
    {
        cout << "Enter a license plate number  --> ";
        cin >> plate;
        cout << "Enter current vehicle's speed --> ";
        cin >> speed;
        cout << "Enter speed limit in the zone --> ";
        cin >> limit;

        overspeed = speed - limit;

        if (overspeed >= 5 && overspeed <= 20)
        {
            ticket = base + 5 * overspeed;
            cout << "A ticket of " << setprecision(2) << fixed << ticket << " is issued to " << plate << "\n\n";

            ticketCount++;
        }
        else if (overspeed > 20  && overspeed <= 50)
        {
            ticket = base + 10 * overspeed;
            cout << "A ticket of " << setprecision(2) << fixed << ticket << " is issued to " << plate << "\n\n";

            ticketCount++;
        }
        else if (overspeed > 50)
        {
            ticket = base + 1000 + (10 * overspeed);
            cout << "A ticket of " << setprecision(2) << fixed << ticket << " is issued to " << plate << "\n\n";

            ticketCount++;
        }
        else
            cout << "No ticket is issued to " << plate << ".\n\n";
    }

    cout << ticketCount << " out of " << totalCount << " times\n";

    return 0;
}

1 个答案:

答案 0 :(得分:1)

正如@IgorTandetnik评论的那样,在获得用户输入后立即添加:

cout << "Enter a license plate number  --> ";
cin >> plate;
if (plate == "NOMORE") break; // add this
cout << "Enter current vehicle's speed --> ";
...

for循环中的条件仅在迭代之间检查,而不是在每个语句之后检查。此流程图总结了它们的行为方式:

For loop flowchart