-2

fsacnfに関するmsdnの説明を見て、コードを変更しようとしました..それは惨事であり、それがどのように機能するかわかりません..たとえば、次の情報を持つファイルxがある場合: "string" 7 3.13 ' x' scanf("%s",&string_input) と書くと、文字列が保存され、次の行に移動しますか? →7まで?そして、私は次のように書きます: char test; fscanf("%c" , &test) -- 'x' にジャンプするか、7 を取り、ASCII 値に変換しますか?

ここに私が試したコードと出力があります:

#include <stdio.h>

FILE *stream;

int main( void )
 {
    long l;
   float fp,fp1;
   char s[81];
    char c,t;

     stream = fopen( "fscanf.out", "w+" );
      if( stream == NULL )
        printf( "The file fscanf.out was not opened\n" );
      else
      {
      fprintf( stream, "%s %d %c%f%ld%f%c", "a-string",48,'y', 5.15,
              65000, 3.14159, 'x' );
  // Security caution!
  // Beware loading data from a file without confirming its size,
  // as it may lead to a buffer overrun situation.
  /* Set pointer to beginning of file: */
  fseek( stream, 0L, SEEK_SET );

  /* Read data back from file: */
  fscanf( stream, "%s", s );
  fscanf( stream, "%c", &t );
fscanf( stream, "%c", &c );

  fscanf( stream, "%f", &fp );
   fscanf( stream, "%f", &fp1 );
  fscanf( stream, "%ld", &l );



  printf( "%s\n", s );
   printf("%c\n" , t);
  printf( "%ld\n", l );
  printf( "%f\n", fp );
  printf( "%c\n", c );

  printf("f\n",fp1);
  getchar();


  fclose( stream );
    }
}

これは出力です:

文字列

-858553460
8.000000
4
へ

理由がわからない

ありがとう!!

4

2 に答える 2

1

あなたの書き込みステートメントは

"%s %d %c%f%ld%f%c", "a-string",48,'y', 5.15, 65000, 3.14159, 'x'

5 番目の引数を as %ldthen として出力する場合は、それも as として渡す必要があります(long)65000。しかし、ほとんどのシステムでは、これは違いはありません。ファイルのコンテンツは次のように表示され、解析されます。

a-string 48 y5.15650003.14159x
^       ^^^
s       |c|
        t fp

s:  "a-string"
t:  ' '
l:  undefined
fp: 8
c:  '4'
fp1: undefined

したがってs、最初の単語から最初のスペースまで一致します。先頭の空白をスキップしないためt、スペース文字に一致します。の 1 桁目と2 桁目に一致します。文字を浮動小数点数として読み取ることができないため、forは次のスペースをスキップし、何も読み取ることができません。forは同じ理由で失敗します。このようなエラーを検出して報告するには、 の結果を確認する必要があります。%cc48fp%ffp1y%ld%lfscanf

于 2012-07-18T13:30:34.040 に答える
1

書式指定子がありません:

printf("f\n",fp1);

次のようにする必要があります。

printf("%f\n",fp1);

さらに重要なこと:の戻り値を確認してくださいfscanf()。成功した割り当ての数を返します。呼び出し1ごとに割り当てが 1 つだけあるはずなので、ここでは呼び出しごとにする必要がありfscanf()ます。失敗した場合fscanf()、変数は変更されません。コード内の変数は初期化されていないため、変数へのfscanf()割り当てに失敗すると、ランダムな値が含まれます。これは次の場合です。

                            /* a-string 48 y 5.15 65000 3.14159 x */
fscanf(stream, "%s", s);    /* ^             (s is assigned "a-string") */
fscanf(stream, "%c", &t);   /*         ^     (t is assigned space)      */
fscanf(stream, "%c", &c);   /*          ^    (c is assigned 4)          */
fscanf(stream, "%f", &fp);  /*           ^   (fp is assigned 8)         */
fscanf(stream, "%f", &fp1); /*             ^ (fail: 'y' is not a float) */
fscanf(stream, "%ld", &l);  /*             ^ (fail: 'y' is not a long)  */
于 2012-07-18T13:18:26.993 に答える