c - 如何读取用户的是/否响应?
问题描述
参加初级编程课程并学习 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;
}
解决方案
您将字符串与单个字符混淆。在这里,您将响应声明为指向 char 的指针。
char* response;
将其更改为
char response;
改变
scanf(" %c", response);
to - 这是传递一个字符变量的地址。%c 接受一个字符。
scanf(" %c", &response);
改变
if (response == "y")
至
如果(响应 == 'y')
字符串文字使用双引号。此外,如果您真的想比较字符串,那也不是正确的方法,您应该查看 strcmp() 函数。
推荐阅读
- c# - 基于父实例创建子类的实例?
- git - 获取“git pull”以忘记缓存的密码
- reactjs - JHipster with React - 如何创建一个独特的路由文件来管理模块文件夹中的所有组件?
- eclipse - 将数据和数据结构从一个 OPC 服务器复制到另一个
- node.js - 如何限制 MongoDB 中每分钟的用户操作?
- react-native - 在 React Native 中显示 Facebook 用户数据时出错
- css - 将一个弹性项目居中并将第二个项目向右对齐任意数量的 px
- c# - 为什么你不能取一个变量并将它自己相乘?
- java - Android - listFiles() 没有列出某些文件
- windows - Pipenv 已安装,但“不存在”