How to read a charde a file and convert to whole

Asked

Viewed 94 times

0

The following code snippet should show the entire value of the single character stored in the file. when I put a letter like 'a' for example works. but when I put this symbol: þ. and several others it shows -2 on the screen. this symbol according to the ASCII table has value 231. the code is this:

#include <stdio.h>

int main() {
    FILE *ptr;
    char c;
    ptr = fopen("teste.txt", "r");
    fscanf(ptr, "%c", &c);
    printf("%d", c);
    return 0;
}

the only thing stored in test.txt is the symbol þ.

  • The symbol þ seems not to have in the table ASCII, I read here with your code and the value that returned was -61. Which SO vc is using?

  • No, the ASCII table only goes up to code 127. You’re taking an extension of it. Then you can vary what returns. The character you are using is probably considered a character multibyte, That’s why you’re creating this mess. If you open the file in some software that allows you to read the file byte by byte, you will probably find 2 or more. There the file is reading only the first.

  • Got it, I’ll see that. My OS is Windows 7 professional

  • Take a look at this table http://ic.unicamp.br/~Everton/classes/hardware/tableASCII.pdf here you can see the character you want, but it is a little different.

1 answer

0

In instruction

printf("%d", c);

the char is automatically converted to int without having to do anything.

It is part of the "integer promotions" rule (see 6.5.2.2p6 in Standard C11 (English))

  • By default the compilers use C89. I never used C11 myself but from what it seems the criticisms are horrible.

  • The rule is the same for C89 and C99, but I do not have a link to the first. As to the criticisms ... the removal of gets() was positive! Other than that (I no longer used the gets() previously) also do not use the novelties of C11 and use few of C99.

  • The only reason I use the C99 is to declare variables in loop loops rest I do not know what changed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.