Limited attempts error?

#include <iostream>
#include <string>

int main()
{

int number = 1232;
int number2 = 2143;
int numb;
int attempts = 0;


while ( attempts < 3){

l1:std::cout<<"Enter number: ";
std::cin>>numb;
if ( numb == number){
std::cout<<"Correct!";
}
else{

std::cout<<"Wrong "<<std::endl;
attempts++;
goto l1;

}
}
if ( attempts == 3){
std::cout<<"TOO MANY ATTEMPTS";
return 1;


}



}

This program won't function properly in terms of "attempts" anyone knows why?

Don't use goto. Especially don't use goto when combined with loops. That's a mess. Just stick with proper loop logic.

Please use code tags. That means wrapping your code around in [code] ... [/code]. Also, you can edit your post instead of double-posting.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>

int main()
{
    const int correct_number = 2143;
    int number;

    const int max_attempts = 3;
    int attempts = 0;
    while (true)
    { 
        std::cout << "Enter number: ";
        std::cin >> number;
        if (number == correct_number) {
            std::cout << "Correct!" << std::endl;
            break; // you got it right, break out of the loop
        } else {
            std::cout << "Wrong. " << std::endl;
            attempts++;
            if (attempts == max_attempts) {
                std::cout << "TOO MANY ATTEMPTS" << std::endl;  
                return 1;
            }  
        }
    }
    
    std::cout << "Hello!" << std::endl;
    return 0;
}
Last edited on
@Ganado - I used "goto" because if you got the input wrong, it would go back to the original question
@Ganado - Where did the 3rd to the last closing curly bracket come from?
I just said edit your post instead of double posting.

I'm not sure what you mean, but here's the same code with aligned brackets.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>

int main()
{
    const int correct_number = 2143;
    int number;

    const int max_attempts = 3;
    int attempts = 0;
    while (true)
    { 
        std::cout << "Enter number: ";
        std::cin >> number;
        if (number == correct_number)
        {
            std::cout << "Correct!" << std::endl;
            break; // you got it right, break out of the loop
        }
        else
        {
            std::cout << "Wrong. " << std::endl;
            attempts++;
            if (attempts == max_attempts)
            {
                std::cout << "TOO MANY ATTEMPTS" << std::endl;  
                return 1;
            }  
        }
    }
    
    std::cout << "Hello!" << std::endl;
    return 0;
}
Topic archived. No new replies allowed.