简体   繁体   English

C Eclipse - 读取文件时打印不需要的 unicode 字符

[英]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.我是 C 的初学者,我正在尝试逐个字符地读取仅包含 Hello world 的文本文件。

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ÿ.但是,output 是 Hello worldÿ。 I have added a new line at the end of Hello world and the ÿ shows up after it.我在 Hello world 的末尾添加了一个新行,并且 ÿ 出现在它之后。 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.我已经使用此代码遍历并打印出一个用 int 填充的文本文件而没有问题,但是从 %d 更改为 %c 会导致打印一个类似的奇怪字符。 I have been told that this is a local issue, potentially related to Eastern languages on my PC or the new Eclipse update.我被告知这是一个本地问题,可能与我 PC 上的东方语言或新的 Eclipse 更新有关。 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.我发现阅读while语句中的字符是最容易且最不容易混淆的,如上所示。 This allows more concise code, and it prevents you from printing the EOF character, as was mentioned in the comments.如评论中所述,这允许更简洁的代码,并且可以防止您打印EOF字符。

As also mentioned in the comments, fgetc() returns and int , not a char , so I made that change here as well.正如评论中提到的, fgetc()返回和int ,而不是char ,所以我也在这里进行了更改。

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.如果可以的话,我还想指出temp对变量来说是一个相当糟糕的名称,因为它的描述性不是很强。 Perhaps consider using something even like c , which is simple.也许考虑使用c类的东西,这很简单。 It's short, and generally makes it known that you're dealing with a character (though it's technically an int )它很短,通常会让人知道你正在处理一个角色(尽管它在技术上是一个int

The issue was fixed by assigning (temp = fgetc(fin)) != EOF .通过分配(temp = fgetc(fin)) != EOF解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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