【问题标题】:How to read all the double numbers from a string using sscanf in c?如何在c中使用sscanf从字符串中读取所有双数?
【发布时间】:2019-12-24 17:30:00
【问题描述】:

我有一个包含不同格式行的文本文件。我想使用 c 读取此文本文件中的所有数字。我想将数字读取为双精度数字。文本文件内容如下:

 1,'            ',  13.8000,2,     0.000,     0.000,   1,   1,1.04500,  11.3183,   1
 2,'            ',  13.8000,2,     0.000,     0.000,   1,   1,0.98000,  19.9495,   1
 17,'1 ',1,   1,   1,  6000.000,   300.000,     0.000,     0.000,     0.000,     0.000,   1
 16,'16',  4000.000,   401.887,  9999.000, -9999.000,1.00000,  0,   200.000,   0.00000, 0.00550

我使用 fopen 读取文件并使用 sscanf 扫描单行内容。我到目前为止的代码如下:

#include <stdio.h>
#include <string.h>

FILE *fptr;
if ((fptr = fopen("rggs.raw","r")) == NULL){
   fprintf(mapFile,"Error! opening file");
}
int line=0;
char input[512];
int total_n = 0;
double ii;
int nn;
while( fgets( input, 512,fptr)){
    line++;
        total_n = 0;
        while (1 == sscanf(input + total_n, "%lf", &ii, &nn)){
            total_n += nn;
            printf(": %lf\n", ii);
        }
}
printf("\n\nEnd of Program\n");
fclose(fptr);

代码的输出是

: 1.000000
: 2.000000
: 17.000000
: 1.000000
: 0.000000
: 0.000000
: 0.000000
: 16.000000
: 0.000000
: 9.000000
: 0.000000
: 0.000000
: 550.000000


End of Program

它不包含我的文本文件中的所有数字。

【问题讨论】:

  • 在 while 循环的条件中,对 sscanf 的调用对说明符有太多参数。当您稍后添加 nn 时,它只是一个垃圾值。
  • 感谢 user312102。我的代码现在可以工作了。

标签: c file scanf fopen


【解决方案1】:

我修改了下面的代码来输出该行中的所有数字。

FILE *fptr;
if ((fptr = fopen("raw_data_IEEE_68.raw","r")) == NULL){
   fprintf(mapFile,"Error! opening file");
}
int line=0;
char input[512];
int total_n = 0;
double ii;
int nn;
while( fgets( input, 512,fptr)){
    line++;
        total_n = 0;
        while (1 == sscanf(input + total_n, "%lf%*[,' ]%n", &ii, &nn)){
            total_n += nn;
            printf(": %lf\n", ii);
        }
}
printf("\n\nEnd of Program\n");
fclose(fptr);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 2012-11-23
    • 2012-06-06
    相关资源
    最近更新 更多