gpt4 book ai didi

c - 当文件包含特殊字符以控制进程时,如何将文件读入 C 中的结构

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

几个小时以来,我一直在尝试将此文件读入我想在我的 C 编程项目中使用的结构。我无法让它与结构一起正常工作。

这是我要读入的文件:

# category
- word to guess
*information to help you to guess the word

- another word to guess
* information to help you to guess the word

# another category
- word to guess
*information to help you to guess the word

- another word to guess
* information to help you to guess the word

这是我的代码(似乎不起作用):

char retazec[50]; // here goes the read in string from the file
char kategoria[50]; // here the category name is stored

i = 0; // index for the array of structures
j = 1;
while (!feof(otazky)) {
fgets(retazec, 50, otazky);
if (strchr(retazec, '#') != NULL) {
printf("%s", retazec);
printf("%d\n", i);
slova[i].kategoria = retazec;
strcpy(kategoria, retazec);
}
if (strchr(retazec, '-') != NULL) {
printf("%s", retazec);
printf("%d\n", i-j);
slova[i-j].slovo = retazec;
j++;
}
if (strchr(retazec, '*') != NULL) {
printf("%s", retazec);
printf("%d\n", i-j);
slova[i-j].napoveda = retazec;
j++;
}
i++;
}

putchar('\n');
putchar('\n');
printf("%s", slova[0].kategoria);
printf("%s", slova[0].slovo);
printf("%s", slova[0].napoveda);

我希望它如何运作:

我有 i 变量来存储结构数组的索引。 j 变量用于修正数组索引。

  1. 读取第一个字符串(#类别)

  2. 如果确实包含'\#',请记住它是什么类别并将其放入slova[i].kategoria(i 为 0)

  3. 它检查其他两个并递增 i

  4. 读取第二个字符串(-字来猜)

  5. 第一个if为false,第二个,如果字符串中包含'-',将其放入slova[i-j] .slovo(i 是 1,j 是 1 所以 i - j = 0)然后它递增 j 因为在下一步中,当程序要读取信息来帮助用户猜测时,i 将是 2,j 也是i - j 再次给我们 0。正如我所想,这 3 个字符串应该在 slova[0] 结构中。但它不起作用,我也找不到原因。

如果有人知道答案,请帮助我。

最佳答案

当您遍历文件时,您正在将数据读入 retazec 缓冲区,然后测试它是类别、单词还是提示。当它是一个类别时,你正在复制

中的类别名称

strcpy(类别, retazec)

然而,当它是一个单词或提示时,您只是设置一个指向读取缓冲区的指针

slova[i-j].napoveda = retazec;

但是下一次读取会破坏该值(覆盖它)。

你应该复制这个值,而不是在那里分配一个指针。您不能分配字符串,您必须复制它们。

关于c - 当文件包含特殊字符以控制进程时,如何将文件读入 C 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15957672/

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