gpt4 book ai didi

c - 将字符串扫描成结构

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

在文本文件中,第一个数字是专辑的数量,第二个是与单个专辑关联的轨道的数量,每个轨道标题前面的数字是标题的字符长度。

现在我无法将每个标题的名称(前面没有数字)扫描到 char **tracks; 中,它也是结构数组的一部分

例如,info[0].tracks[0] 应该打印出字符串“Like an umbrella”。

示例文本文件:

1
17
16 Like an umbrella
...
15 Dynasty Warrior

代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct album
{
int num_tracks;
char **tracks;

};

int main(int argc, char *argv[]){
int numbALBUMS=0, numbCharInTrack=0;
int i=0,j=0;

FILE *albums;
albums = fopen (argv[1], "r");

fscanf(albums, "%d", &numbALBUMS);
struct album *info = (struct album*)malloc(numbALBUMS * sizeof(struct album));

for(i=0;i<numbALBUMS;i++){
fscanf(albums, "%d", &info[i].num_tracks);
info[i].tracks = malloc(sizeof(char*) * info[i].num_tracks);

for(j=0;j<info[i].num_tracks;j++){
fscanf(albums, "%d", &numbCharInTrack);
info[i].tracks[j] = malloc(sizeof(char) * numbCharInTrack);

//NEED HELP HERE

}
}


fclose(albums);
return 0;

}

最佳答案

试试这个

fscanf(albums, "%d", &numbCharInTrack);
info[i].tracks[j] = malloc(sizeof(char) * (numbCharInTrack+1));//+1 for NUL, sizeof(char) is always 1(by standard)
fscanf(albums, " %[^\n]", info[i].tracks[j]);//Space to skip the previous space

关于c - 将字符串扫描成结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26705463/

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