gpt4 book ai didi

c - Scanf 接受 EOF 之前的数字(不以空格分隔)

转载 作者:太空宇宙 更新时间:2023-11-04 03:51:57 25 4
gpt4 key购买 nike

我需要 scanf 来读取数字,包括在 EOF 之前输入的数字(没有空格或在输入此数字后输入,只是 EOF - 如“1 2 3 4EOF” - 4 未被读取)。我的代码如下所示:

for (i = 0; i < 100; i++)
{
if ((scanf ("%d", &number) != 1 && !feof(stdin)))
{
printf ("Wrong input.\n");
return (0);
}

if (feof(stdin) && count == 0)
{
printf("Empty input.\n");
return 0;
}

if (feof(stdin)) break;

field[i] = number;
count++;
}

需要调整的部分在哪里,以接受 EOF 之前未分隔的最后输入的数字?非常感谢,我真的看不出来..

最佳答案

造成破坏的是 if (feof(stdin)) break;。如果您没有从 scanf() 获得 1,您应该只在 EOF 处中断。在你的例子中,系统知道它已经到达 EOF,但它也成功转换了一个值,它通过从 scanf() 返回 1 告诉你这一点,但你去了前面并忽略成功转换的值,因为也检测到 EOF。

你可能应该使用:

#include <stdio.h>

int main(void)
{
int field[100];
int count = 0;
int n;

for (int i = 0; i < 100; i++)
{
int number;
if ((n = scanf("%d", &number)) != 1)
break;
printf("-- %d: %d (%d)\n", i, number, n);
field[i] = number;
count++;
}

if (n == 0)
{
printf("Wrong input.\n");
return 1;
}
else if (ferror(stdin))
{
printf("I/O error on stdin\n");
return 1;
}
else if (feof(stdin) && count == 0)
{
printf("Empty input.\n");
return 1;
}

printf("Count: %d\n", count);
for (int j = 0; j < count; j++)
printf("%d: %d\n", j, field[j]);
return 0;
}

关于c - Scanf 接受 EOF 之前的数字(不以空格分隔),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20020491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com