Kevin
Kevin

Reputation: 37

Scanning string into structure

Inside the text file, the first number is number of albums, second is number of tracks associated with a single album, and the number infront of each track title is the character length of the title.

Right now I am having trouble scanning in the name of each individual title (without the number in front) into char **tracks; which is also part of an array of Structs

For example, info[0].tracks[0] should print out the string "Like an umbrella".

Example Text File:

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

Code:

#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;

}

Upvotes: 1

Views: 819

Answers (1)

BLUEPIXY
BLUEPIXY

Reputation: 40145

try this

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

Upvotes: 2

Related Questions