gpt4 book ai didi

c - fscanf 如何处理不同的变量类型?

转载 作者:行者123 更新时间:2023-11-30 20:16:21 25 4
gpt4 key购买 nike

我正在查看 fscanf 的 MSDN 文档。我尝试更改文档中的示例代码,但它没有按我的预期工作。

例如,如果我有一个文件“x”,其内容为:

"string" 7 3.13 'x'

执行scanf("%s", string_input)后,将数据"string"读入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 );
}
}

这是输出:

 
  
a-string-8585534608.0000004f

为什么是这样的输出?我期待的是:

a-string0650005.15y3.14159

最佳答案

缺少格式说明符:

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) */

关于c - fscanf 如何处理不同的变量类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11542186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com