Reputation: 1
This is my code:
for(b = 0; b < 3; b++)
{
int col1 = 0;
printf("b= %d\t" , b);
fgets(payload, sizeof payload, f2);
fputs(payload, stdout);
char *token;
token = strtok(payload, " ");
token = strtok(NULL, " ");
token = strtok(NULL, " ");
while ( token != NULL)
{
int pp;
sscanf(token, "%d", &pp);
token = strtok(NULL, " ");
printf("%d\n" ,pp);
grapharray[b][col1++] = pp;
}
}
In this code, I am taking some values from the file line by line and copying them into a 2D array. I am skipping the first two values from the file. Everything is working fine except my loop -- it copies the value correctly into location grapharray[b][col1]
, where b==0
, but then skips b==1
and directly moves to b==2
and copies the next row of the file at grapharray[2][col1]
. Can anyone help me with this problem? Thanks so much, I will be grateful.
Upvotes: 0
Views: 244
Reputation: 2068
If you are trying to read lines, one at a time from a file, fgets() is not the best tool. If there are more characters in the line that you have room for in the target array, these characters will not be read.
See Using fgets to read strings from file in C
Upvotes: 0
Reputation: 7132
if your second
token = strtok(NULL, " ");
returns NULL, your while loop won't be entered and it will look as if b=2 was discarded => check with a debugger the value of token and maybe review your parser.
EDIT:
If your parsed data contain a tab (\t) instead of a space, this is likely to happen. Maybe you want to use " \t" in your tokenizer.
Upvotes: 3