2

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?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Rafael Dias
  • 83
  • 2
  • 9
  • 2
    Probably want `fscanf(f, " %c", &j);` - add space. – chux - Reinstate Monica Oct 06 '14 at 23:48
  • 1
    To avoid trailing garbage make your loop be `while ( fscanf(f, " %c", &j) == 1 )`. [More info](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) – M.M Oct 07 '14 at 00:07
  • Also consider checking the result of the `fscanf` within the `default` case, otherwise your program will break on encountering a string with letters in it – M.M Oct 07 '14 at 00:09
  • See [`while (!feof(file))` is always wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) for information on why your `while (feof(f) == 0)` loop is a bad idea. – Jonathan Leffler Oct 07 '14 at 03:08

2 Answers2

1

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;
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

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;

    }

}
Farouq Jouti
  • 1,657
  • 9
  • 15
  • 1
    1) Code has an interesting infinite loop. Consider if `j = fgetc(f);` results in `j == EOF` and `char` is `unsigned char`. Code keeps putting back an `char`. 2) ` i = atoi(&t);` is UB. – chux - Reinstate Monica Oct 07 '14 at 01:08