2016-07-22 70 views
-4

我已經在c中編寫了下面的代碼來讀取文本文件中的單詞,但是代碼不工作,請更正它。 我有一個文件a.txt中,在它:
編碼

所以我想這個詞「編碼」的存入數組b中。讀取單詞格式的文本文件(單個單詞排成一列)

q=fopen("a.txt","r"); 
d=fgetc(q);//q is pointer to text file 
while(d!=EOF) 
      { 
      i=0; 
      while((d!='\n')&&(d!=EOF)); 
      { 
       b[i++]=d; 
       d=fgetc(q); 
      } 
      b[i]='\0'; 
      if(d==EOF) 
       break; 
      d=fgetc(q); 
     } 
+1

問題尋求幫助調試(「爲什麼不是這個代碼的工作?」)必須包括所期望的行爲,一個特定的問題或錯誤以及在問題本身中重現它所需的最短代碼 –

+0

@pcluddite代碼是否正確? –

+2

如果它不像你說的那樣工作,那麼它可能不是。 –

回答

0

如果你不malloc阿婷內存,那麼下面就我的做法

int c; 
char myword[20]; // max characters to store is 20 
int i=0; 
FILE* ptr=fopen("38518211","r"); 
if (ptr==NULL){ 
printf("Can't open the file"); 
} 
else{ 
while(i<19 && (c=fgetc(ptr)) != EOF) 
    myword[i++]=c; 
} 
if((c=fgetc(ptr)) != EOF) 
printf("Original string is truncated to fit into alloted space\n"); 
myword[i]='\0'; // Null terminating the string 
printf("String from file %s\n",myword); 
fclose(ptr); 
相關問題