I have a file that is organized line by line and the structure of all lines was defined by me but the contents of each line can increase or decrease according to two variables that the same line contains.
Line Example: 1 Andre 2 0 5 13 05 2011 4 13 05 2011
‘1’ represents the user ID
‘Andre’ represents the name associated to the ID
‘2 0’ subdivides: ‘2’ represents how many movies the user as taken home AND ‘0’ represents how many movies reservations the user has.
So far the line is following the pattern %d %s %d %d and they can be stored in the variables I want.
Now the hard part comes. Depending on the ‘2 0’ part, the program knows that has to read the pattern %d %d %d %d (‘5 13 05 2011’ and ‘4 13 05 2011’ – represent dates of movies taken home) 2 times and also the program knows that after reading 2 times the previous pattern it knows that i doesn’t need to read anything else due to the zero part in ‘2 0’.
Example of line with more data: 1 Andre 2 1 5 13 05 2011 4 13 05 2011 7 14 05 2011
‘2 1’
The ‘2’ part tells the program that in that line it should read ‘5 13 05 2011’ and ‘4 13 05 2011’ to variable_one[i][4] (example)
The ‘1’ part tells the program that in that line it should read ‘7 14 05 2011’ to variable_two[i][4] (example)
I’m using fscanf(file, "%d %s %d %d", &id[i],&nomes[i],&livros_num[i][0],&livros_num[i][1]); to read ‘1 Andre 2 0’ but how can i read the rest of the line according to ‘2 0’?
After your first call of fscanf, you need to loop depending on the variables you read. You seem to have already realized that the
int‘s you read in your first call determine the number of extra reads you need in the line.