【问题标题】:Why doesn't this break terminate the program, but instead proceeds to the next operation?为什么这个 break 不终止程序,而是继续下一个操作?
【发布时间】:2015-06-18 10:35:04
【问题描述】:

如果我在3次尝试后没有输入正确的密码,如何使用此代码退出程序?

break 并未终止程序,而是转到下一个代码块。

    int cod = 2334;
    while (true){
      cout << "Introduce your password." << endl;
      cin >> cod;       
       while(pass!=cod){
         int counter =1;
         cout << "Wrong password. You have three trials" << endl;
         cin >> cod;                    
         counter++;
         if (counter == 4)
            break;
    }

【问题讨论】:

  • 计数器永远不会达到 4。

标签: c++ while-loop break


【解决方案1】:

break 退出最里面的块。你有 2 while 所以它只会逃避内部的。此外,您的计数器永远不会达到 4,因为您每次循环都将其重置为 1。试试这个:

int cod = 2334;
int counter = 1;

cout << "Introduce your password." << endl;
cin >> cod;       
while(pass!=cod && counter < 4){    
    cout << "Wrong password. You have three trials" << endl;
    cin >> cod;                    
    counter++;
}

【讨论】:

    猜你喜欢
    • 2014-01-08
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多