c - 如何在 C 中使用 EOF 标准输入

标签 c stdin scanf feof

在遇到 EOF 之前,我需要将坐标输入到数组中,但我的代码有问题。我用的是ctrl+Z,ctrl+D

int main()
{
    int x[1000],y[1000];
    int n=0,nr=0,a,b,i;
    printf("Enter the coordinates:\n");
    while(scanf ( "%d %d ", &a, &b) == 2)
    {
     x[n]=a;
     y[n]=b;
     n++;
    }
    if (!feof(stdin))
    {
       printf("Wrong\n");
    }
    else
    {
       for(i=0;i<n;i++)
       printf("%d %d\n", x[i], y[i]);
    }

  return 0;
}

最佳答案

我建议使用

while(!feof(stdin) && scanf ( "%d %d ", &a, &b) == 2)

实际上最好测试feof 之后(不是之前!)一些输入操作,所以:

while (scanf("%d %d ", &a, &b) == 2 && !feof(stdin))

顺便说一句,在许多系统上 stdinline 缓冲的,至少对于交互式终端是这样(但当 stdinpipe(7) 时可能不是), 请参阅 setvbuf(3)

在 Linux 和 POSIX 上,您可能会考虑使用 getline(3) 阅读每一行(或者甚至使用 readline(3) 如果从终端读取,因为 readline 提供编辑能力),然后用例如解析该行sscanf(3) (也许还使用 %n)或 strtol(3)

关于c - 如何在 C 中使用 EOF 标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8094702/

相关文章:

c# - .NET 应用程序如何重定向其自己的标准输入流?

C语言: Search text file for a "word" and store the value into int and flout type variables

c - 如何读取 C 中空格后的下一个字符?

c - 如何使用openMP为MPI程序制作makefile?

c - 如何从通过指针调用函数的函数返回指针到返回指针的函数?

c - 使用动态链接器包装 glibc 函数

python - Postgresql 如何使用 CSV COPY TO STDIN 进行冲突更新?

传递给函数时更改数组指针的值

c - fgets() 无法正常工作

C - scanf 行为异常