在遇到 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))
顺便说一句,在许多系统上 stdin
是 line 缓冲的,至少对于交互式终端是这样(但当 stdin 是 pipe(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/