在用户使用eof按下回车键之前,如何从用户那里获取输入整数?

How can I get input integers from user until he press enter by using eof?

我们开始编写 C 代码,但我无法解决我的 h.w 因为我不知道如何从用户那里获取输入(整数),直到他按 20 30 10 40 之类的回车键,然后通过使用完成伊夫。 这是不起作用的部分代码,

printf("Students, please enter heights!\n");
   while((scanf("%d",&height))!=EOF)
    {
        if(height>0)
        {
            avg_girls=avg_girls+height;
            counter_girls++;
        }

        else
        {
            avg_boys=avg_boys+height;
            counter_boys++;
        }  
    }

我进入了无限循环 非常感谢。

您可以使用 scanf 和 array 来实现。

while (scanf("%d*[^\n]", &height[i++]) == 1 && i < height_len);

scanf 将 return 正确读取的项目数。

然后处理你的身高。

虽然从一行中读取未知数量的整数的更好方法是将整行读入足够大小的缓冲区,然后使用 strtol(利用其 endptr 参数将缓冲区中的位置更新为 1-character 超过最后转换的值),您可以使用 scanf 并完成相同的事情。

使用 scanf 从一行输入中读取多个整数的一种方法是简单地读取每个字符并确认它不是 '\n' 字符或 EOF。如果该字符不是数字(或数字前面的 '-' 符号 - thanks Ajay Brahmakshatriya),则直接获取下一个字符。如果字符是数字,将其放回 stdinungetc,然后在更新女孩或男孩之前调用 scanf 验证转换 基于输入符号的平均值。

您可以执行以下操作:

    int height;

    fputs ("enter heights: ", stdout);

    while ((height = getchar()) != '\n' && height != EOF) {
        /* if not '-' and not digit, go read next char */
        if (height != '-' && !isdigit (height))
            continue;
        ungetc (height, stdin);     /* was digit, put it back in stdin */
        if (scanf ("%d", &height) == 1) {   /* now read with scanf */
            if (height > 0) {       /* postive val, add to girls */
                avg_girls += height;
                counter_girls++;
            }
            else {                  /* negative val, add to boys */
                avg_boys += height;
                counter_boys++;
            }
        }
    }

isspace()宏由ctype.hheader提供。如果不能包含其他 header,那么只需手动检查 height 是否为数字,例如

    if (height != '-' && (height < '0' || '9' < height))
        continue;

(请记住,您正在阅读 个字符 getchar(),因此请与 '0''9' 的 ASCII 字符进行比较)

另一种方法是将整行输入读入缓冲区,然后在处理缓冲区时重复调用 sscanf 转换整数,另外使用 "%n" 说明符报告字符数被对 sscanf 的调用所消耗。 (例如,使用 "%d%n" 并提供指向 int 的指针来保存 "%n" 提供的值)然后您可以保留 运行 总计 offset 从缓冲区的开头添加到指向位置 sscanf 的指针以供下一次读取。

任何一种方法都可以,但是阅读 line-at-a-time 比起尝试使用 scanfstdin 本身,阅读 line-at-a-time 的陷阱要少得多。