如何扫描文本文件并将字符输入到数组中?

我正在尝试扫描文本文件并将字符输入到数组中。

char newArray[500];

FILE *fp2;
fp2 = fopen("LeftPattern_Color.txt", "r");

char ch;

while ((ch = fgetc(fp2)) != EOF)
    {
        int i = 0;  
        newArray[i] = ch;
        i++;
    }

fclose(fp2);

But when I printed out the characters to test if the inputted characters are in newArray[500], there was nothing printed.

for(int i = 0; i < 500; i++)
{
  printf("%c", newArray[i]);
}
评论
长大嫁你
长大嫁你

as said in remark you need to use int to be able to compare with EOF and int i = 0; must be outside of the for else you always write in newArray[0]

还要注意,您编写了数组的所有500个元素,即使您更正了代码,如果文件少于500个字符,也将打印未初始化的元素,您只需要编写从0到i不包括在内的元素

Anyway you can just use fread

size_n nread = fread(newArray, sizeof(newArray), fp2)
点赞
评论