简体   繁体   English

如何在C中使用EOF stdin

[英]how use EOF stdin in C

I need to input coordinates into an array until EOF is encountered, but something is wrong in my code. 我需要将坐标输入到数组中,直到遇到EOF,但我的代码中出现了错误。 I used ctrl+Z, ctrl+D 我用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;
}

I suggest using 我建议使用

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

and actually it is better to test feof after (not before!) some input operation, so: 实际上最好 (之前没有!)某些输入操作之后测试feof ,因此:

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

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) 顺便说一句,在许多系统上, stdin缓冲的,至少是交互式终端(但是当stdin管道(7)时可能不行),参见setvbuf(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 eg sscanf(3) (perhaps also using %n ) or strtol(3) 在Linux和POSIX上,您可以考虑使用getline(3)读取每一行如果从终端读取,甚至使用readline(3) ,因为readline提供编辑功能),然后使用例如sscanf(3)解析该行(也许还使用%n )或strtol(3)

The only real problem that I see in your code is the extra spaces in the scanf format string. 我在代码中看到的唯一真正的问题是scanf格式字符串中的额外空格。 Those spaces tell scanf to consume whitespace character on the input, which makes scanf not return to your code until it hits a non-whitespace character (such as a letter, a number, punctuation, or EOF). 这些空格告诉scanf消耗输入上的空格字符,这使得scanf不会返回到您的代码,直到它遇到非空白字符(例如字母,数字,标点符号或EOF)。

The result is that after typing two numbers and then Enter , you have to type Ctrl - D ( Ctrl - Z in DOS/Windows) twice before your program escapes the while loop. 结果是在键入两个数字然后输入后 ,您必须在程序转义while循环之前两次键入Ctrl - D (在DOS / Windows中为Ctrl - Z )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM