Can't figure out why my print statement keeps printing out twice

Viewed 70

hey guys so I have this code i'm working with and it's doing everything i need it to do, however, i can't figure out why my printf is printing out twice for level. here is the code.

while(fgets(str_read, sizeof(str_read)-1 , fptr)!= NULL)
    sscanf(str_read, "%d ", &somearray->level);
    printf("level: %d\n", somearray->level);

also if there is anything else i could work on im open to feed back. i'm working with a .txt file that has the following setup:

int
name
int
name
int
name
2 Answers

You need to check the return value from sscanf. On lines that don't contain an integer, it will return 0. In that case, somearray->level will be unchanged, so you'll print it a second time.

One possible solution is:

while(fgets(str_read, sizeof(str_read)-1 , fptr)!= NULL)
    if (sscanf(str_read, "%d ", &somearray->level) == 1)
        printf("level: %d\n", somearray->level);

This attempts the sscanf for every line, but only prints the result if a value was found.

Another solution would be to keep track of even vs. odd lines, and only attempt the sscanf on odd lines.

First off, I'm going to assume your code has braces around it since otherwise, it would only print once at the end (braces control what's in a loop body, not indentation):

while(fgets(str_read, sizeof(str_read)-1 , fptr)!= NULL) {
    sscanf(str_read, "%d ", &somearray->level);
    printf("level: %d\n", somearray->level);
}

That gels with what you're seeing. If your text file consists of alternating integers and non-integer names, every second sscanf will fail because a name cannot be treated as an integer. Since you don't check the return value, you just blindly assume the conversion worked and print the value that was previously in somearray->level.

Calls to the scanf family of function should generally include a check to ensure everything was correctly scanned, something like:

if (sscanf(str_read, "%d ", &somearray->level) != 1) {
    handleBadScan();
}
Related