cswitch-statementscanfungetc

fscanf and switch not working


I'm trying to read this .txt file:

( 1 2 ( 3 4 ( 5

with this code:

#include <stdio.h>

int main() {
  FILE* f = fopen("teste.txt", "r");
  int i;
  char j;

  while (feof(f) == 0){
    fscanf(f, "%c", &j);

    switch (j) {

      case '(':
        printf("%c ", j);
        break;

      default:
        ungetc(j,f);
        fscanf(f, "%d", &i);
        printf("%d ", i);
        break;

    }
  }
  return 0;
}

The output is:

( 1 2 2 ( 3 4 4 ( 5 5

and it should be:

( 1 2 ( 3 4 ( 5

What am I doing wrong?


Solution

  • 1) Use int j; fgets() returns an unsigned char or EOF 257 different values. Using a char loses information.

    2) Do not use feof()

    // while (feof(f) == 0){ 
    //  fscanf(f, "%c", &j);
    while (fscanf(f, " %c", &j) == 1) {  // note space before %c
    

    3) Test fscanf() return value

    // fscanf(f, "%d", &i);    
    if (fscanf(f, "%d", &i) != 1) break;