简体   繁体   中英

calling scanf inside do while loop is breaking the loop

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM