fscanf and switch not working

90 views Asked by At

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?

2

There are 2 answers

0
chux - Reinstate Monica On BEST ANSWER

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;
1
Farouq Jouti On

use fgetc instead of fscanf , try this

    #include <stdio.h>

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

    j = fgetc(f);

    switch (j){

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

    default:
    ungetc(j,f);
    t = fgetc(f);
    i = atoi(&t);
    printf("%d ", i);
    break;

    }

}