How to store special characters in strings and print to files?

Asked

Viewed 26 times

-2

Recently I’ve been working on a C project that involves printing some strings in a txt file. However, when I put special characters and accents are printed some strange symbols, like ‡ and Æ. I made an example code showing more or less what I need.

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

int main(int argc, char *argv[]) {
    setlocale(LC_ALL, "Portuguese");

char teste[100];

printf("Frase: "); /*Usei a Frase "Gabriel Fogaça não perguntará em vão" para os testes*/
gets(teste);

printf("\n\nResultado: %s\n", teste);

FILE* arq = fopen("teste.txt", "w+");

    fprintf(arq, "%s", teste);

fclose(arq);

return 0;

}

By the way, when I use "setlocale" the print gets bugged up at the prompt, but that’s the least. What I really need is to be able to print the string in the txt file.

1 answer

-2

The problem is that you are setting the locale to an encoding (probably ISO 8859-1, which uses only one byte per character) but the terminal must be using UTF-8 (variable number of bytes per character) which is the default nowadays.

Try running the program without calling the setlocale function.

  • I circled without using this function and actually the result in the terminal normalized, but in the txt file continue to appear symbols in place of the special characters :(

  • It is, but then probably the problem is in the charset configuration of your editor, which is not UTF-8. It is not your program’s fault.

  • Aaah got it. I’ll try to change the settings then. Thanks a lot for the help!!

  • I was able to change the settings of the editor and now the charset is in UTF-8. Still the error continues :(

Browser other questions tagged

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