Reputation: 385
I'm reading in a text file where certain lines begin with an asterisk, then other lines contain numbers indicating the size of a rectangle. I'm very confused on how I should be extracting this information though. I'm initially trying to use fgets()
to read the strings and then sscanf
to read the integers, as seen;
while(fgets(line, MAX_CHARS, infile) != NULL) {
if(line[0] == '*') {
printf("%s\n", line);
}
sscanf(line, "%d%d", &height, &width);
printf("height: %d, width: %d\n", height, width);
}
but it's printing like this;
*Case #1
height: 0, width: 0
height: 10, width: 20
....
*Case #2: Shape
height: 10, width: 20
height: 7, width: 7
....
Should I be reading this file character by character instead?
Sample input: (the height and width aren't updated right away)
*Case #1
10 20
X
X
XXX
*Case #2: Shape
7 7
XX
XX
X
Upvotes: 0
Views: 106
Reputation: 206577
You forgot to add the else
part after the if
.
while(fgets(line, MAX_CHARS, infile) != NULL) {
if(line[0] == '*') {
printf("%s\n", line);
}
// Missing piece
else {
sscanf(line, "%d%d", &height, &width);
printf("height: %d, width: %d\n", height, width);
}
}
Upvotes: 1