2013-02-16 99 views
2

我試圖從duom.txt文件讀取文本並將每個字符存儲到數組中。 但我沒有得到正確的答案。 我的代碼有什麼問題?如何從文本文件中讀取文本並將每個字符存儲在數組中

# include <stdio.h> 
# include <stdlib.h> 
int main() 
{ 
FILE *in; 
char ch,str[100],cw; 
int j,i = 0; 

in=fopen("duom.txt","r"); 


if(in){ 
    while(!feof(in)){ 
    ch=getc(in); 
    str[i] = ch; 
    i++; 
} 
} 

for(j=0;j<i;j++){ 
      printf("%c",str[i]); 
} 
printf("\n"); 
    fclose(in); 


    system("pause"); 
return 0; 
} 

duom.txt文件:

My name is Lukas 
+3

我知道這是不是回答你的問題,但你的代碼格式是令人厭惡的。嘗試並實踐適當的縮進和句法「美化」,以免您未來可能會迷惑自己。 – tsujp 2013-02-16 17:08:43

回答

1
  1. 龜etc()返回一個int這樣類型的chint

  2. feof()告訴你是否有讀過文件的結尾。這意味着你的while循環將被執行超過所需的一次。

1

你應該把j,而不是i在打印循環:

for(j=0;j<i;j++){ 
     printf("%c",str[i]); // <-- here, it must be `str[j]` 
} 

這就是爲什麼你應該使用永諾有意義的變量名!

1

程序中有一個小錯字。

for(j=0;j<i;j++){ 
    printf("%c",str[j]); //str[j] instead of str[i] 
0

有在代碼中的一個小錯誤是

for(j=0;j<i;j++){ 
     printf("%c",str[i]); // <-- here, it must be `str[j]` 
} 

的變量導致diaster在程序 的變化,從而對其進行編輯,並嘗試

相關問題