简体   繁体   English

在 do while 循环中调用 scanf 会打破循环

[英]calling scanf inside do while loop is breaking the loop

I have a do while loop.我有一个do while循环。 When I run it without scanf() , it runs properly.当我在没有scanf()的情况下运行它时,它运行正常。 But if I enter a scanf() it breaks the loop?但是如果我输入scanf()会打破循环吗? Why???为什么???

The code:代码:

With scanf()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()但是当我在没有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 function 中的guessed变量前面添加&

scanf("%d", &guessed);

An explanation of how scanf works can be seen here .可以在此处查看scanf工作原理的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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