Home > Back-end >  calling scanf inside do while loop is breaking the loop
calling scanf inside do while loop is breaking the loop

Time:10-02

I have a do while loop. When I run it without scanf(), it runs properly. But if I enter a scanf() it breaks the loop! Why???

The code:

With scanf()

void main(){
    int num = prng() % 100, guessed, guesses = 0;
    bool  win = false;
    printf("The Game Begins. You Have To Guess A Number\n");
    do{ //A do while loop untill the user guesses the correct number
        printf("Guess a number\n");
        scanf("%d", guessed);
        guesses  ;
    }while (!check(guessed, num));
    printf("Yayy!!! You won the game in %d guesses!!", guesses); //Message after guessing the correct number
    return;
}

This breaks the loop instantly:

> .\a.exe
The Game Begins. You Have To Guess A Number
Guess a number
5
> 

But when I run it without the scanf()

void main(){
    int num = prng() % 100, guessed, guesses = 0;
    bool  win = false;
    printf("The Game Begins. You Have To Guess A Number\n");
    do{ //A do while loop untill the user guesses the correct number
        printf("Guess a number\n");
        guessed = num;
        // scanf("%d", guessed);
        guesses  ;
    }while (!check(guessed, num));
    printf("Yayy!!! You won the game in %d guesses!!", guesses); //Message after guessing the correct number
    return;
}

It works fine!!

> .\a.exe
The Game Begins. You Have To Guess A Number
Guess a number
Hurrayyy!!!! You got the number!!!!!!!!!Yayy!!! You won the game in 1 guesses!!
> 

Can you explain what is the actual problem?

CodePudding user response:

You need to add & in front of guessed variable within the scanf function.

scanf("%d", &guessed);

An explanation of how scanf works can be seen here.

  • Related