首页 > 解决方案 > 如何读取用户的是/否响应?

问题描述

参加初级编程课程并学习 C。这是我遇到的第一个重大障碍,昨天花了 6 个多小时,找不到解决方案,所以我放弃了,决定寻求帮助。作业是用基于布尔值的循环构建一个猜数游戏(尚未进入随机数生成部分),其中提示用户在正确猜测后再次玩并回答 y 或 n。我尝试了很多东西,无论选择什么选项(这是它在当前状态下所做的),循环要么终止,要么无休止地循环,我不确定我做错了什么。这是我的代码。提前致谢。

#include <stdio.h>
#include <stdbool.h>

int main()
{
    int num = 5; /* temp placeholder for testing */
    int guess;
    char* response;
    bool running = true;

    while (running)
    {
        printf("Guess a number: ");
        scanf("%d", &guess);
            
        if (guess < num)
        {
            printf("That's too low.\n\n");
        }
        else if (guess > num)
        {
            printf("That's too high.\n\n");
        }
        else
        {
            printf("That is correct.\n\n");
            guess = 0;
            printf("Play again? (y/n): ");
            scanf(" %c", response);
            printf("Response: [%s]", response);
            printf("\n");
            
            if (response == "y")
            {
                running = true;
            }
            else
            {
                running = false;
            }
        }
    }
    return 0;
}

标签: c

解决方案


您将字符串与单个字符混淆。在这里,您将响应声明为指向 char 的指针。

 char* response; 

将其更改为

 char response;

改变

 scanf(" %c", response);

to - 这是传递一个字符变量的地址。%c 接受一个字符。

  scanf(" %c", &response);

改变

if (response == "y") 

如果(响应 == 'y')

字符串文字使用双引号。此外,如果您真的想比较字符串,那也不是正确的方法,您应该查看 strcmp() 函数。


推荐阅读