-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()
コールを移動しました。
使用したすべての機能のドキュメントをお読みください。 'fopen()'の直後に 'ferror()'を呼び出すことは潜在的に*未定義の動作*です。あなたは 'NULL'ポインタを渡すことができます。 –
よろしくお願いします。編集されました。 – azochz
'index'はどのようにして得られますか? –