Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

scanf

 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:

i 10

i 12

d 10

d 12

(The character/integer are tab separated). My output is:

id: i, value: 10

bad input

id: i, value: 12

bad input

id: d, value: 10

bad input

id: d, value: 12

bad input

WHAT am I doing wrong? "Bad input" should ONLY be printed if the file is incorrectly formatted. The file above demonstrates a properly formatted file. I don't understand how r == 2 and r != 2 at the same time (both conditions are somehow met).

like image 842
Sara Avatar asked Sep 20 '15 13:09

Sara


2 Answers

Use

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

Might 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 your next iteration your id get \n and num gets the character.

But when you put extra white space before %c which tells fscanf() to ignore whitespaces(including Tab, space or newline). Thus your fscanf() gets two parameter(character and number).

like image 121
ashiquzzaman33 Avatar answered Sep 28 '22 11:09

ashiquzzaman33


Please 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 at the end in fscanf.

In your file, lines are terminated with \n. In next read it does not go well.

like image 20
Austin Avatar answered Sep 28 '22 10:09

Austin