vincelam1998 vincelam1998 - 1 month ago 12
C++ Question

Why does my C++ sentinel loop continue after the sentinel value is entered?

When I enter the string "NOMORE" it continues to the next line where it asks me for the vehicle speed. It only stops the loops when it finishes the for loop. How can I make it so that it stops immediately when "NOMORE" is entered? Thanks for any help. I truly appreciate it. And sorry for wasting your time if I did :(

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

qxz qxz
Answer

As @IgorTandetnik commented, add this right after you get the user input:

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

The condition in a for loop is only checked between iterations, not after every statement. This flowchart sums up how they behave:

For loop flowchart

Comments