Karl Joonas Volke Karl Joonas Volke - 1 month ago 13
C Question

What happens to scanf if the entered value from a file is empty?

I'm using command line to input a text file to a program, which uses the info from the file to display other values accoring what was in that text file.

test.exe < input.txt (Command line)

File looks like this:


abc 123

qwe 456

Number 2 tells me how many things program has to read. (Named COUNT in code)

double number[MAXVALUE];
for(i = 0; i < COUNT; i++)
scanf("%s %lf", name[i], &number[i]);

This what the input code looks like.

Now, what happens is if I put 3 as COUNT, the program will try to read 3 lines and displays the 3rd line as gibberish.
How can I prevent the scanf from operating, if the values entered are non-existant?

I tired
if(scanf(....) != 1)
but it doesn't seem to work.


First of all, avoid invoking undefined behavior %lf is for reading double, not int.

Then, the return value of scanf() is useful for checking if reading is successful.

Quote from N1570 The scanf function, paragraph 3:

The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.

Here is an example of improved code:

double number[MAXVALUE];
char name[MAXNAME][MAXLENGTH];    
for(i = 0; i < COUNT; i++)
        if (scanf("%s %lf", name[i], &number[i]) != 2)
                fputs("read error\n", stderr);
                exit(1); /* stdlib.h should be included to use this */