Why doesn't this break terminate the program, but instead proceeds to the next operation?

65 views Asked by At

How to exit the program with this code when I don't write the correct password after 3 trials?

The break is not terminating the program, but instead it goes to the next code block.

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

There are 1 answers

0
Code Different On

break exit the inner most block. You have 2 while so it will only escape the inner one. Also your counter will never reach 4 because you keep resetting it to 1 with each loop. Try this instead:

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