Fscanf - I don't know what I'm doing wrong here

char id; int num, r; if (argc != 2) { printf("error\n"); exit(1); } FILE *file = fopen(argv[1], "r"); if (file == NULL) { printf("error\n"); exit(1); } while ((r = fscanf(file, "%c\t%d", &id, &num)) != EOF) { if(r == 2) { printf("id: %c, value: %d\n", id, num); } else if (r!=2) { printf("bad input\n"); } } 

The file I'm trying to read looks like this:

i 10

i 12

d 10

d 12

(The character / integer is divided into a tab). My way out:

id: i, value: 10

failed input

id: i, value: 12

failed input

id: d, value: 10

failed input

id: d, value: 12

failed input

What am I doing wrong? Poor input should ONLY print if the file is not formatted correctly. The above file shows a properly formatted file. I do not understand how r == 2 and r != 2 at the same time (both conditions are somehow fulfilled).

+5
source share
2 answers

Use

 while((r = fscanf(file, " %c\t%d", &id, &num)) != EOF) //Whitespace before %c 

You can solve your problem. Because when you use

 fscanf(file, "%c\t%d", &id, &num) 

Then it leaves a newline character, which is consumed in the next iteration. As the next iteration, your id gets \n and num gets the character.

But when you put an extra space before %c , which tells fscanf() ignore spaces (including Tab, space or new line). This way your fscanf() gets two parameters (character and number).

+4
source

Change

 while ((r = fscanf(file, "%c\t%d", &id, &num)) != EOF) { 

to

  while ((r = fscanf(file, "%c\t%d\n", &id, &num)) != EOF) { 

Adding \ n to the end in fscanf.

In your file, the lines end with \ n. In the next reading, this does not go well.

+2
source

All Articles