gpt4 book ai didi

c - 读取 .txt 文件并获取单词/整数作为字符串

转载 作者:行者123 更新时间:2023-11-30 20:35:14 24 4
gpt4 key购买 nike

我有一个 .txt 文件:

apple 123 12 1 7 3 222
danger 1234 11 223 44 87 65
what 2322 6567 54
its 9128 88 66 12 12

编辑:新问题。我尝试使用 fgets 使用 while 函数一次获取 1 行,然后使用 sscanf 遍历该行并将每个单词/整数放入其自己的字符串中。因此理论上第一个 term_in 应该是 apple,然后是 123,然后是 12,依此类推。好的,现在可以编译了,但是不起作用。没有打印任何内容。

int offset;
char line[1000];
FILE *fp;
char term_in[1000];
fp = fopen(argv[1], "r");

while (fgets(line, sizeof(line), fp) != NULL) {
char *data = line;
while (sscanf(line, " %s%n", term_in, &offset) == 1) {
data += offset;
printf("%s", term_in);
}
}

最佳答案

你已经很接近了。这是一个小的改编 - 一个有效的 MCVE ( Minimal, Complete, Verifiable Example ):

#include <stdio.h>

int main(void)
{
int offset;
char line[1000];
FILE *fp = stdin; // Important but simple change
char term_in[1000];

while (fgets(line, sizeof(line), fp) != NULL) {
char *data = line;
while (sscanf(data, "%s%n", term_in, &offset) == 1) { // Changes
data += offset;
printf("[%s]\n", term_in); // Trivial change
}
}

return 0;
}

这是一个示例运行(它被称为 rl59.c 并编译为 rl59):

$  rl59 <<< 'Once upon a time, there was a country that held nice, civilized presidential elections.'
[Once]
[upon]
[a]
[time,]
[there]
[was]
[a]
[country]
[that]
[held]
[nice,]
[civilized]
[presidential]
[elections.]
$

并给定一个多行输入文件:

So she went into the garden
to cut a cabbage-leaf
to make an apple-pie
and at the same time
a great she-bear coming down the street
pops its head into the shop
What no soap
So he died
and she very imprudently married the Barber
and there were present
the Picninnies
and the Joblillies
and the Garyulies
and the great Panjandrum himself
with the little round button at top
and they all fell to playing the game of catch-as-catch-can
till the gunpowder ran out at the heels of their boots

输出是:

[So]
[she]
[went]
[into]
[the]
[garden]
[to]
[cut]
[a]
[cabbage-leaf]
[to]
[make]
[an]
[apple-pie]
[and]
[at]
[the]
[same]
[time]
[a]
[great]
[she-bear]
[coming]
[down]
[the]
[street]
[pops]
[its]
[head]
[into]
[the]
[shop]
[What]
[no]
[soap]
[So]
[he]
[died]
[and]
[she]
[very]
[imprudently]
[married]
[the]
[Barber]
[and]
[there]
[were]
[present]
[the]
[Picninnies]
[and]
[the]
[Joblillies]
[and]
[the]
[Garyulies]
[and]
[the]
[great]
[Panjandrum]
[himself]
[with]
[the]
[little]
[round]
[button]
[at]
[top]
[and]
[they]
[all]
[fell]
[to]
[playing]
[the]
[game]
[of]
[catch-as-catch-can]
[till]
[the]
[gunpowder]
[ran]
[out]
[at]
[the]
[heels]
[of]
[their]
[boots]

关于c - 读取 .txt 文件并获取单词/整数作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40060724/

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