2017-09-10 22 views
-2

私は比較的簡単なCコードのビットを持っています - ファイルを取り込みますdict.txt(1行に1語、すべて英字と小文字)。文字列はコンソールに文字列として出力されません

目的は、各単語を単語という配列に「ロード」し、その単語を印刷してからEOFまで繰り返すことです。

現在、printf("%s\n", ptr)は、意図したとおり、コンソールに空白行を表示するのではなく、文字列を表示します。 これはなぜですか、どのように修正できますか?

#include <stdbool.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 
#include <string.h> 

#include "dictionary.h" 

int main(void) { 

// open given dictionary 
FILE* dict; 
dict = fopen("dict.txt", "r"); 

char word[46]; 
int index = 0; // to navigate word array 
char *ptr = word; 

// start loading words 
for (int c = fgetc(dict); c != EOF; c = fgetc(dict)) 
{ 
    // allow only alphabetical characters and apostrophes 
    if (isalpha(c) || (c == '\'' && index > 0)) 
    { 
     // append character to word 
     word[index] = c-97; 

     index++; 

    } // we must have found a whole word 
    else if (index > 0) 
    { 
     // terminate current word 
     word[index] = '\0'; 

     printf("%s\n", ptr); 

     // prepare for next word 
     index = 0; 
    } 

} 

// check whether there was an error 
if (ferror(dict)) 
{ 
    fclose(dict); 
    printf("Error reading.\n"); 
    return 1; 
} 



// close text 
fclose(dict); 

return 0; 
} 

編集: NULLエラーを回避するために、ループの後にferror()コールを移動しました。

+2

使用したすべての機能のドキュメントをお読みください。 'fopen()'の直後に 'ferror()'を呼び出すことは潜在的に*未定義の動作*です。あなたは 'NULL'ポインタを渡すことができます。 –

+0

よろしくお願いします。編集されました。 – azochz

+0

'index'はどのようにして得られますか? –

答えて

1

あなたは意味、

word[index] = c; 

あなたはisalpha()cがASCII文字であることを保証しますので、特別に、任意の計算を実行する必要はありません。

fopen()が、それはNULLポインタを返し、そうferror()をパラメータとしてNULLポインタと呼ばれることになるとそれが未定義の動作で、代わりにdict != NULLいることを確認し失敗した場合、この

  • を修正。
関連する問題