gpt4 book ai didi

c - fscanf 是否可以同时返回零和消耗输入?

转载 作者:太空狗 更新时间:2023-10-29 15:21:19 27 4
gpt4 key购买 nike

fscanf 是否可以同时消耗输入和返回零?例如,如果我写

int res;
int k = fscanf(f, "%d", &res);

并检查 k == 0,我能否确定对同一文件 f 的下一次 fscanf 调用会在在调用 fscanf 之前文件所在的同一位置?

最佳答案

dasblinkenlight 中概述的主题的另一个变体的 answer是:

for (int i = 0; i < 20; i++)
{
int rc;
int number;
if ((rc = scanf(" this is the time for all good men (all %d of them)", &number)) == 0)
{
char remnant[4096];
if (fgets(remnant, sizeof(remnant), stdin) == 0)
printf("Puzzling — can't happen, but did!\n");
else
{
printf("The input did not match what was expected.\n");
printf("Stopped reading at: [%s]\n", remnant);
}
}
else if (rc == 1)
printf("%d: There are %d men!\n", i + 1, number);
else
{
printf("Got EOF\n");
break;
}
}

在包含以下内容的文件上尝试:

this is the time for all good men (all 3 of them)
this is the time for all good men (all 33 men)
this is the
time for

all good men
(all

333 of

them)
this is the time for all good men to come to the aid of the party!

等等

输出:

1: There are 3 men!
2: There are 33 men!
The input did not match what was expected.
Stopped reading at: [men)
]
4: There are 333 men!
The input did not match what was expected.
Stopped reading at: [to come to the aid of the party!
]
Got EOF

请注意,第二个句子的转换成功,即使在“men)”(预期为“of them)”上匹配失败)。没有可靠的方法来获取有关最后一次计数(非抑制,非 %n)转换后匹配失败的信息。下一次匹配尝试完全失败,但是 fgets() 清理了输入(读取该行的剩余部分),然后后续尝试成功了,因为格式字符串中的空格匹配任意序列输入中的空白区域。在示例数据的最后一行中,信息“这是所有好人的时代”被成功读取,但是“to come to the aid of the party”不匹配。

关于c - fscanf 是否可以同时返回零和消耗输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47839125/

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