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

标签 c do-while

获取输入,直到它是 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/

相关文章:

java - 无法让 while 循环正常工作-java

从 C 调用带有字符串参数的 Go 函数?

java - 需要在类中实现do、while循环

c - 为什么我的静态堆栈不起作用?

c - 可见的副作用顺序

java - 为什么第一个 do while 循环在满足 while 条件时不结束?

java - 在java中只返回奇数(int)的方法

c - 使用 do while 的基于菜单的程序

Python C API 在不构建元组的情况下返回多个值/对象

c - 如何在C中使用printf和scanf处理char16_t或char32_t?