0

I have a simple file as below:

1
3
a 7

and when I run the code below, I get some unexpected result. I initially try to read the first two integers and then read the character a and number 7. There is no white space after the number 1 or 3.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


main(int argc, char **argv)
{
    FILE *f;
    f = fopen(argv[1],"r");
    int  num1, num2, num3;
    char t;

    fscanf(f, "%d",&num1);
    fscanf(f, "%d",&num2);


    fscanf(f, "%c %d", &t, &num3);
    printf("%c %d\n", t, num3);
}

EDIT:

Input is the file with the content:

    1
    3
    a 7

and the output is a new line and some garbage. Expected output should be a 7

EDIT 2: it reads correctly 1 and 3. Then trying to read a single character a if fails

user3764893
  • 687
  • 5
  • 16
  • 33

1 Answers1

3

Loooks at what happens when you run this:

fscanf(f, "%d",&num1);

skips whitespace (of which there is none), then reads an integer (1)

fscanf(f, "%d",&num2);

skips whitespace (the newline at the end of the first line) then reads an integer (3)

fscanf(f, "%c %d", &t, &num3);

reads the next caharcter from the input (a newline), then skips whitespace (none) and tries to read an integer. The next input character is 'a', so this fails, and the fscanf call returns 1 without writing anything into num3.

So the problem you are having is that due to the fact that %c does NOT skip whitespace, you are reading the whitespace (newline) instead of the character you expect. The most obvious solution is to add a space () to the format to skip whitespace:

fscanf(f, " %c%d", &t, &num3);

Note that I've also removed the space before %d, as it is redundant (%d always skips whitespace).

In addition, it is always a good idea to check the return value of fscanf to make sure it is reading the number of input items you expect.

Chris Dodd
  • 111,130
  • 12
  • 123
  • 212