我有一个文件头有两行,其余部分包含两列 double 据,例如
0.0030556304 -0.0078125
第一列长 16 个字符,第二列长 17 个字符,后面有一个空格和“\n”。
我读取此文件的代码是
nscan = fscanf(sound_file, "%lf %lf %c", &value1,
&value2,
&termch);
我使用 termch
进一步测试换行符。
我尝试过
nscan = fscanf(sound_file, "%16lf %16lf %c", &value1,
&value2,
&termch);
也是。
但是当我 printf 时
printf("%f %f\n", value1, value2);
结果是
-0.000000 -0.000000
我错过了什么吗?
最佳答案
fscanf(sound_file, "%lf %lf %c"...
没有按照您的想法进行。
"%c"
之前的空格会占用所有空白,包括 ' '
和 '\n'
。下面的 "%c"
将消耗下一个 char
(此时必须是非空白)(如果有)。
最好使用 fgets()
读取所有文件行,然后使用 sscanf()
扫描缓冲区
char buf[100];
// Read 2 header lines and toss
if (fgets(buf, sizeof buf, sound_file) == NULL) Handle_EOForIOError();
if (fgets(buf, sizeof buf, sound_file) == NULL) Handle_EOForIOError();
// Insure code is using a type the match format specifiers
// Could be a problem in OP's unposted code.
double value1, value2;
while (fgets(buf, sizeof buf, sound_file) != NULL) [
int cnt = sscanf(buf, "%lf%lf", &value1, &value2);
if (cnt != 2) Handle_MissingData();
else Use(value1, value2);
}
<小时/>
fscanf("%lf",...
扫描可选的前导空格,然后扫描 double 。"之前的前导
。""
不需要 %lf"
fscanf("%16lf",...
将扫描的非空白 char
总数限制为 16 个。
关于C 读取带有前导空格的 double 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26193504/