fscanf如何使用不同的变量类型?

时间:2012-07-18 13:09:36

标签: c file variables scanf

我正在查看有关fsacnf的msdn解释,并尝试更改代码..这是一场灾难,我不明白它是如何工作的.. 如果我有一个文件x有这个信息:“string”7 3.13'x' 当我写scanf(“%s”,& string_input)以便保存字符串然后它进入下一行? - >到7? 我现在写信: char测试; 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 );
    }
}

这是输出:

a-string

-858553460
8.000000
4
f

无法理解为什么

谢谢!

2 个答案:

答案 0 :(得分:1)

缺少格式说明符:

printf("f\n",fp1);

应该是:

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

更重要的是:检查fscanf() 的返回值。它返回成功分配的数量:此处每次调用应为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)  */

答案 1 :(得分:1)

你的写声明是

  

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

如果您将第五个参数打印为%ld,那么您还应将其作为(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与空格字符匹配,因为%c不会跳过前导空格。 c匹配48的第一个数字,fp匹配第二个数字。 %f fp1将跳过下一个空格,然后无法读取任何内容,因为字符y无法读取为浮点数。 %ld的{​​{1}}会因同样的原因失败。您应该检查%l的结果以检测并报告此类错误。