gpt4 book ai didi

c - 简单的 if 语句和 scanf 不适合我

转载 作者:行者123 更新时间:2023-11-30 21:18:12 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>

int main() {
char choice[1];
printf("Do you like oranges? y/n: \n");
scanf("%s\n", choice);
if (choice == "y")
printf("I do too! \n");
else if (choice == "n")
printf("Screw you then! \n");
else
printf("You did not type it correctly.");
return 0;
}

当它运行时询问我代码中的 scanf(""); 部分时,它不会继续,直到我输入两件事,这会导致 else 要运行的函数。

示例:

Do you like oranges? y/n:

y
y

You did not type it correctly.

最佳答案

首先,删除 scanf 格式中 %s 后面的空格

scanf("%s", choice);

scanf 格式中的空格具有特殊含义:它指示它“跳过所有空格”,这使得它继续读取输入流,直到遇到第一个非空格字符。这就是迫使它等待,直到您“输入两件事”。

其次,C中的字符串比较是通过strcmp函数完成的。您不能通过 == 运算符来比较字符串。使用 strcmp 或确保只比较一个字符。要么这个

if (strcmp(choice, "y") == 0)

或者那个

if (choice[0] == 'y')

第三,长度为 1 的字符串无法放入长度为 1 的缓冲区中。您需要一个额外的缓冲区条目来存储终止 \0 字符。如果您坚持将 y/n 响应读取为字符串,则需要一个至少 2 个字符长的缓冲区。但这仍然很危险,因为您总是可以输入更长的字符串并溢出缓冲区。至少使用 %1s 说明符来读取字符串。

关于c - 简单的 if 语句和 scanf 不适合我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27537099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com