gpt4 book ai didi

c - C语言中如何避免空格、回车键或非数字输入? scanf 读取整数值

转载 作者:行者123 更新时间:2023-11-30 19:32:01 25 4
gpt4 key购买 nike

获取输入,直到它是 0 到 23 之间的整数。

int n;    
do
{
printf("Enter height: ");
scanf("%d", &n);
} while ( n < 0 || n > 23);

以某种方式向 while 添加 EOFNULL

最佳答案

我唯一看到的是输入“24”本身不会停止循环,因此您需要将条件更改为:

while ( n < 0 || n > 24);

NULL 不是问题,因为您无法从标准输入获取 NULL。 NULL 表示指向字节号 0 的地址。当您使用当前运行线程的堆栈上的内存调用 scanf 时,这种情况不会发生。

关于 stdin 中的 EOF,您可以在此处获取更多信息 End of File(EOF) of Standard input stream (stdin) .

关于使用 scanf,我建议阅读: Disadvantages of scanf .

<小时/>

编辑:这是最好的做法。摆脱 scanf 并使用 fgets 和 strtol,如以下示例(取自 This SO answer )

char *end;
char buf[LINE_MAX];
int n = 0;

do {
if (!fgets(buf, sizeof buf, stdin))
break;

// remove \n
buf[strlen(buf) - 1] = '\0';

//Get integer from line
n = strtol(buf, &end, 10);
// making sure that a valid input was given (i.e. a number) and its value
// You might also want to check that strlen(end) is zero, to avoid input like "213 abcde", depends on you
} while ((end != buf) && ( (n > 24 || n < 0)));

关于c - C语言中如何避免空格、回车键或非数字输入? scanf 读取整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47550732/

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