Question

I've got a file that is formatted like this

A New Day Has Come (Radio Remix); 239
Ten Days; 227
Goodbye's (The Saddest Word); 198
Prayer; 313
I Surrender; 271
At Last; 209
Sorry For Love; 301

How would I use fscanf to grab the string, and also the number following the semicolon? I tried this

for(track = 0; track < albums[size].num_tracks; ++track){

    fscanf(fileptr,"%s;%i",albums[size].tracks[track].name,albums[size].tracks[track].length);

    //print out the tracks
    printf("Track number %i : %s", track, &albums[size].tracks[track].name);
}

However, when the printf happens, the whole string isn't printed, rather something like

Track number 0 : A 
Track number 1 : New
Track number 2 : Day
etc...

So as you can see, the code is capturing the individual words for some reason, rather than the entire string before the semi colon. Which expression would I use to grab the entire string? Edited for spelling

Était-ce utile?

La solution

While fscanf might not be the best function to use in this case, formally one can still be use it to grab the string that ends with ; by using the following format specifier

fscanf(fileptr, "%[^;];%i",
  albums[size].tracks[track].name,
  &albums[size].tracks[track].length);

This will require the input file to adhere to very strict format requirements though. Note also that if your albums[size].tracks[track].length is an int object, then & operator is required before albums[size].tracks[track].length. When %i format specifier is used in fscanf it requies a pointer to int as argument.

Also, your printf does not look right. It should be

printf("Track number %i : %s", track, albums[size].tracks[track].name);

That & before albums[size].tracks[track].name is not supposed to be there.

Autres conseils

You shouldn't fscanf is for formatted data. Your data isn't really formatted in a way friendly to fscanf. You'd be better off reading the whole line and then just searching for the semicolon.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top