gpt4 book ai didi

c - 通过使用一系列指针从结构访问字符串

转载 作者:行者123 更新时间:2023-11-30 16:36:13 25 4
gpt4 key购买 nike

typedef struct {
char numeVolum[50]; ////this is what interests us!!!
short int anPublicare;
unsigned char stare;
int idPersoana;
} TVolum;

typedef struct {
char numeAutor[50];
char codTara[2];
int nrVolume;
TVolum* volume; /////this is what interests us!!!
} TAutor;

这两个结构都是动态分配的!listaAutori[0] 是指向 TAutor 结构的指针数组!(可以得出listaAutori是TAutor**类型)

fgets(listaAutori[0] -> numeAutor, 50, input); 
fgets(listaAutori[0] -> codTara, 3, input);
fgets(listaAutori[0] -> volume[0].numeVolum, 53, input);

前两个 fget 读起来很好。但第三个没有给我任何输出。

printf("\nNUme primul volum al lui Agatha: %s\n", listaAutori[0] -> volume[0].numeVolum);

换句话说,我有两个结构,A和B。在 B 里面,我有一根绳子。 (指向字符的指针)

结构体A中有一个指针pB。并且有一个指向 A 的指针数组。

像这样:

包含 pA 元素 -> 结构 A -> pB -> 结构 B -> 我的字符串的指针数组。

我正在尝试从文件中读取一行,并将该字符串存储在 numeVolum[50] 字符串中。我访问 TVolum 的唯一方法是使用指向 TAutor 的指针。

我不知道什么不起作用, printf 没有给我任何输出。它应该打印一些东西。(我从中读取数据的文件包含每一行的信息)

Autor* alocaAutor(int nrVolume) 
{
TAutor* autor = (TAutor*)calloc(1, sizeof(TAutor));
autor -> volume = (TVolum*)calloc(nrVolume, sizeof(TVolum));
autor -> nrVolume = nrVolume;
return autor;
}

TAutor** alocaAutori(int nrAutori, int* nrVolumeAutor)
{
int i;
TAutor** vectorAutori = (TAutor**)calloc(nrAutori, sizeof(TAutor*));
for(i = 0; i < nrAutori; i++) {
vectorAutori[i] = alocaAutor(nrVolumeAutor[i]);
}
return vectorAutori;
}

输入文件示例:

2 
1
1
Agatha Christie
UK
Ultimul caz al lui Hercule Poirot

我百分百肯定它会读取最后一行之前的所有内容。然后,当我尝试从 TVolume 读取字符串内的最后一行时,它根本不起作用。

最佳答案

char *fgets(char *str, int n, FILE *stream)

在读取了 n-1 个字符后停止 ( source )。由于第二个 fgets 中的 n 值为 3,因此它仅读取输入文件中的 UK。后面的换行符还没有被读取。然后由第三个​​ fgets 读取它,它立即遇到换行符,不会进一步读取。因此,不会读取输入文件中的最后一行。

您编辑的代码(在您的评论中)之所以有效,是因为 fscanf 读取该换行符并在其处停止,让 fgets 读取最后一行。

关于c - 通过使用一系列指针从结构访问字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48600668/

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