简体   繁体   中英

C Eclipse - Printing unwanted unicode characters when reading file

I am a beginner at C, and am trying to read a text file containing only Hello world character by character.

My code is:

#include <stdio.h>
#include <ctype.h>
FILE *fin = fopen("t1.txt", "r");
char temp = fgetc(fin);
printf("%c", temp);
while (temp != EOF) {
    temp = fgetc(fin);
    printf("%c", temp);
}
fclose(fin);

However, the output is Hello worldÿ. I have added a new line at the end of Hello world and the ÿ shows up after it. I've used this code to traverse and print out a text file filled with int without problems, but changing from %d to %c causes a similarly strange character to print. I have been told that this is a local issue, potentially related to Eastern languages on my PC or the new Eclipse update. What may be the issue here, and how can I fix it? Thanks.

#include <stdio.h>
#include <ctype.h>
FILE *fin = fopen("t1.txt", "r");
int temp;
while ((temp = fgetc(fin)) != EOF) {
    printf("%c", temp);
}
fclose(fin);

I find it easiest and least confusing to read the character in the while statement, as shown above. This allows more concise code, and it prevents you from printing the EOF character, as was mentioned in the comments.

As also mentioned in the comments, fgetc() returns and int , not a char , so I made that change here as well.

If I may, I'd also like to point out that temp is a rather bad name for a variable because it's not very descriptive. Perhaps consider using something even like c , which is simple. It's short, and generally makes it known that you're dealing with a character (though it's technically an int )

The issue was fixed by assigning (temp = fgetc(fin)) != EOF .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM