如何在 C 中使用 EOF 标准输入 [英] how use EOF stdin in C

查看:73
本文介绍了如何在 C 中使用 EOF 标准输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将坐标输入到一个数组中,直到遇到 EOF,但我的代码有问题.我用过 ctrl+Z, ctrl+D

I need to input coordinates into an array until EOF is encountered, but something is wrong in my code. I used 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 after(不是之前!)一些输入操作,所以:

and actually it is better to test feof after (not before!) some input operation, so:

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

顺便说一句,在许多系统上,stdinline 缓冲的,至少在交互式终端上是这样(但当 stdinpipe(7)),参见 setvbuf(3)

BTW, on many systems stdin is line buffered, at least with interactive terminals (but perhaps not when stdin is a pipe(7)), see setvbuf(3)

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

On Linux & POSIX you might consider reading every line with getline(3) (or even with readline(3) if reading from the terminal, since readline offers editing abilities), then parsing that line with e.g. sscanf(3) (perhaps also using %n) or strtol(3)

这篇关于如何在 C 中使用 EOF 标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆