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

最佳答案

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

10-08 17:02