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
  • 697
  • 5
  • 16
  • 33
  • 2
    check the return value of fscanf – Sourav Ghosh Nov 27 '15 at 20:04
  • 1
    Please clarify your problem statement: **exact** input, **exact** expected output, **exact** actual output along with results of each `scanf`. And, as @SouravGhosh already stated: **always** verify the results of `scanf`. Use a debugger. – too honest for this site Nov 27 '15 at 20:06
  • Possible duplicate of [Reading newline from previous input when reading from keyboard with scanf()](http://stackoverflow.com/questions/29905009/reading-newline-from-previous-input-when-reading-from-keyboard-with-scanf) – n. m. could be an AI Nov 27 '15 at 20:11
  • Verifying the return value of `scanf` is fine and dandy, but the return value won't tell you *why* it has failed. – n. m. could be an AI Nov 27 '15 at 20:16

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
  • 119,907
  • 13
  • 134
  • 226