使用 sscanf 解析文本文件的整数和浮点值 [英] Parsing Integer and Float Values of a Text File with sscanf

查看:249
本文介绍了使用 sscanf 解析文本文件的整数和浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将带有这些字段的文件解析为整数和浮点变量,我尝试使用 fscanf、strtok、sscanf 来做到这一点.但它们都不起作用!

I want to parse such a file with these fields into integer and float variables,I tried to do this using fscanf,strtok,sscanf. But none of them works!

文件的一些行:

fed18 5.7 12.7 144997 8087 267345 100776
fedora18 24.9 25.3 253566 10501 126282 118157
fed18 5.9 12.7 145005 8094 267345 100785
fedora18 23.3 25.3 253576 10507 126282 118169
fed18 6.2 12.7 145013 8100 267345 100789

运行以下代码返回错误值!我搜索的时候不知道有什么问题,每个人都使用这样的代码,并且对他们来说效果很好!

Running the following code returns wrong values! I don't know what's the problem as I search, everybody use such this code and it works properly for them!

 while(fgets(str,512,fp)!= NULL)//read file line by line
{
char *tokenstring = str;
uint64_t netrx,nettx,vbd_rd,vbd_wr;
double cpu, mem;
char a[10],b[10],c[10],d[10],e[10],f[10],g[10];
   sscanf(tokenstring, "%s ,%[^' '],%[^' '],%[^' '],%[^' '],%[^' '],%[^' ']",g, a, b, c, d, e, f);
   cpu = atof(a);
   mem = atof(b);
   nettx  = atoi(c);
   netrx  = atoi(d);
   vbd_rd  = atoi(e);
   vbd_wr  = atoi(f);
   printf("%s %f %f %ld %ld %ld %ld\n",g,cpu,mem,netrx,nettx,vbd_rd,vbd_wr);
}
fclose(fp);

输出如下:

fed18 38.000000 1.000000 0 0 0 0
fedora18 38.000000 1.000000 0 0 0 0
fed18 38.000000 1.000000 0 0 0 0
fedora18 38.000000 1.000000 0 0 0 0
fed18 38.000000 1.000000 0 0 0 0

我使用 bash 脚本和使用 awk 编辑了原始文本文件,....原始行采用以下格式:

I edited the original text file with a bash script and using awk ,.... The original lines were in this format:

     fed18 --b---       3616    6.3    1052640   12.7    1052672      12.7     3    1   125864     6023    1        0   254349    93082    7412662    4730752    0
  fedora18 --b---       4711    2.4    2101216   25.3    2101248      25.3     3    1   249151     8636    1        0   126083   113505    3306934    5992656    0

我使用 bash 脚本选择了一些列.也许这导致了问题!

I selected some columns using a bash script. maybe this caused the problem!

我注释了使用函数atoiatof 的行,但仍然输出错误的值.

I commented the lines of using function atoi or atof but still output wrong values.

推荐答案

如果你总是希望参数之间有一个空格,你可以简单地格式化字符串并避免使用 atoi, atof:

If you always expect a single space between arguments you can simply your format string and obviate the need for atoi, atof:

while(fgets(str,512,fp)!= NULL)//read file line by line
{
    char *tokenstring = str;
    uint64_t netrx,nettx,vbd_rd,vbd_wr;
    char g[10];
    double cpu, mem;
    long int c, d, e, f;
    sscanf(tokenstring, "%s %lf %lf %lu %lu %lu %lu", g, &cpu, &mem, &nettx, &netrx, &vbd_rd, &vbd_wr);
    printf("%s %f %f %ld %ld %ld %ld\n",g,cpu,mem,netrx,nettx,vbd_rd,vbd_wr);
}
fclose(fp);

这篇关于使用 sscanf 解析文本文件的整数和浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆