2016-10-09 40 views
-1

当我输入字符串“NOMORE”时,它会继续下一行,询问车速。它只在完成for循环时停止循环。如何在“NOMORE”输入时立即停止?谢谢你的帮助。我真的很感激它。为什么我的C++标记循环在输入标记值后继续?

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

for循环的条件仅之间检查:很遗憾浪费了,如果我没:(

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

'CIN >>板;如果(板== “曲子”)破;' –

+2

你的循环之所以这么做,是因为这就是你编写程序的原因。 –

+0

这是否意味着我不需要一个哨兵呢? – vincelam1998

回答

1

你的时间作为@IgorTandetnik评论,你得到的用户输入之后添加此权。迭代,每个语句后没有该流程图总结了他们的言行举止:

For loop flowchart

+0

应该提示Igor通过重新评估他的评论IMO来发布答案。 – StoryTeller

+0

我想你是对的,但我仍然会提供相同的答案。另外我加了解释 – qxz

+0

谢谢谢谢@Igor Tandetnik – vincelam1998

相关问题