2

ここでのprintfステートメントは、ファイル内の最後の単語のみを出力します。何故ですか?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
    FILE *fp;
    int c;
    char string[100];
    fp = fopen("exam.txt", "r");
    c = getc(fp);
    while(c!=EOF)
    { 
        fscanf(fp, "%s", string);
        c = getc(fp);
    }
    fclose(fp);
    printf("%s", string);
    return 0; 

}
4

1 に答える 1

3

最後に一度だけ印刷するので...

printf("%s", string); 

このループ内で印刷する必要があります。

while(c!=EOF)
{ 
    fscanf(fp, "%99s", string);
    printf("%s\n", string);  // now you can see the files as you read it.
     c = getc(fp);
} 

各行を見たい場合。string毎回上書きしているだけです。

また、使用する前に初期化することはありませんint c

の内訳fscanf()

 fscanf(fp,       // read from here   (file pointer to your file)
        "%99s",   // read this format (string up to 99 characters)
         string); // store the data here (your char array)

ループ状態は、次の文字がEOFではないときにファイルの終わりを意味します(すべてのデータがファイルから読み取られた後に発生する状態)

それで:

while (we're not at the end of the file)
     read up a line and store it in string
     get the next character

アルゴリズムはその文字列内の何もチェックせず、単に文字列に書き込むだけであることに注意してください。これにより、その中のデータが毎回上書きされます。これが、ファイルの最後の行だけが表示される理由です。書き続けstringて、EOF文字が表示され、whileループから抜け出す前に、最後に読んだ行がたまたまあるからです。

于 2012-12-19T18:17:17.490 に答える