c - 从文件中选择 float

标签 c file-io scanf

我想从文件中选择 float 。我认为解决方案是这样的:

while ( (ch= getc(fp)) != EOF )
{
   if( isdigit(ch))
      //do some stuff
}

但是后来我看到,通过这种方法我只能得到整数(但我想要 float )。所以我看了看,发现了这个:

while( (fscanf(fp, "%lf", &n ) == 1)
   //do some stuff

我还查看了 fscanf() 的定义以及它所说的其他内容..

Return Value

On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ.

但是,我不明白 while( (fscanf(fp, "%lf", &n ) == 1)。如果 fscanf() 读取一个 float 将返回 1,否则将返回其他内容?

最佳答案

如果读取并转换一个浮点值,代码中的 fscanf 调用将返回 1。如果您有一个要求两次转换的格式(例如,"%lf %d"),它会返回 2 表示成功。简而言之,它将返回您在格式字符串中成功解析的 % 格式的数量。

如果输入不是 float ,则fscanf 将返回0,因此循环将结束。或者,如果出现错误或您已到达文件末尾,它将返回 EOF,这也会中断循环。

关于c - 从文件中选择 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21134312/

相关文章:

java - 在文件中有效地存储 float 和 short 值的数组

python - 从大文件(~2.5GB)读取并存储到 python 列表时出现 MemoryError

c - 对 'setlinebuf' 的 undefined reference

c - C语言获取int后获取用户字符串

python - 将指针字典保存到文件

c++ - 是否存在轻量级且免安装的数据库系统?

c - GDB 看不到除 main 之外的源文件,这是由 makefile 引起的吗?

c - 在 C 中打印队列时丢失元素

c - fscanf 不从文件读取

php - 从 C 调用 PHP 运行时函数作为链接库