C scanf()问题? [英] C scanf() issues?

查看:96
本文介绍了C scanf()问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个简单的数字猜测游戏中,scanf()在main中第二次不起作用.如果有人能解释为什么不起作用以及如何解决它,我将不胜感激. 关于如何清除此代码的任何提示?谢谢!

In this simple guess-the-number game, scanf() is not working the second time in main. I would really appreciate if someone could explain why doesn't work and how to fix it. Any tips on how to clean this code up?. Thank you!

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int guessed = 0;
int guesses = 0;
int total_guesses = 0;
int range_top = 1;
int generate_random_number()
{
    srand(time(NULL));
    return (rand() % range_top);
}
void take_guess(int num)
{
    int guess;
    printf("what is your guess:  ");
    scanf("%i",&guess);
    if(guess == num)
    {
        guessed = 1;
    }
    else if(guess>num)
    {
        printf("Your guess was too high,\n");
    }
    else 
    {
        printf("Your guess was too low.\n");
    }

}
int main(void)
{
    printf("This is a game in C\n");
    printf("Would you like to play? (y/n): ");
    char play;
    scanf("%c",&play);
    while(play == 'y')
    {
        printf("I am thinking of a number between 0 and %i\n",range_top);
        int num = generate_random_number();
        while(guessed ==0)
        {
            take_guess(num);
            guesses++;
        }
        printf("It took you ");
        printf("%i",guesses);
        printf(" guesses to win.\n");
        printf("Would you like to play again? (y/n): ");
        scanf("%c",&play);
        guessed = 0;
        guesses = 0;
        total_guesses+=guesses;

    }
    printf("goodbye!");
}

推荐答案

这是经典的新手错误.

scanf("%c",&play);

将在您读取take_guess中的数字后读取输入流中剩余的换行符.

will read the newline character that is left in the input stream after you read the number in take_guess.

使用

scanf(" %c",&play);

相反.

当格​​式说明符中在%c之前有一个空格字符时,该函数将从输入流中读取第一个非空格字符.否则,它将从输入流中读取第一个可用字符.

When you have a whitespace character before %c in the format specifier, the function will read the first non-whitespace character from the input stream. Otherwise, it will read the first available character from the input stream.

这篇关于C scanf()问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆