将字符串扫描到结构中

时间:2014-11-02 22:59:53

标签: c string file-io structure

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

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

例如,info[0].tracks[0]应打印出字符串“Like a 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;

}

1 个答案:

答案 0 :(得分:2)

试试这个

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