使用FSCANF从ints和floats中读取C 中的浮子

Using fscanf to read from tabbed file with ints and floats in C++

本文关键字:读取 floats FSCANF ints 使用      更新时间:2023-10-16

我已经在stackoverflow和其他站点上寻找了一天左右,我找不到解决问题的解决方案。有些类似,但我似乎无法使它们起作用。

我有一个tab-delimited .txt文件。一条线包含一个标题,此后的500行包含一个整数,整数,一个浮点,整数和整数,并按照该顺序为单位。我的函数应该读取每行的第一个和第三个值(第一个整数和浮点)。它跳过第一行。这是在循环的情况下进行的,因为我需要能够处理不同长度的文件。但是,它被困在循环中。我将其设置为输出均值,但它只是永远输出零。

void HISTS::readMeans(int rnum) {
    int r;
    char skip[500];
    int index = 0; int area = 0; double mean = 0; int min = 0; int max = 0;
    FILE *datafile = fopen(fileName,"r");
    if(datafile == NULL) cout << "No such file!n";
    else {
            //ignore the first line of the file
            r = fscanf(datafile,"%sn",skip);
            cout << skip << endl; //just to check
            //this is the problematic code
            do {
                    r = fscanf(datafile,"%dt%dt%ft%dt%dn",&index,&area,&mean,&min,&max);
                    cout << mean << " ";
            } while(feof(datafile) != 1)
    }
    fclose(datafile);
}

这是我要阅读的格式的示例数据文件:

        Area        Mean        Min        Max
1       262144      202.448     160        687
2       262144      201.586     155        646
3       262144      201.803     156        771

谢谢!

编辑:我说我需要阅读第一个和第三个价值,我知道我正在阅读所有值。最终,我需要 store 第一个和第三个值,但是为了简洁起见,我切割了那部分。并不是说这个评论是简短的。

您应该这样做C 样式,

#include <iostream>
#include <fstream>
int main() {
  std::ifstream inf("file.txt");
  if (!inf) { exit(1); }
  int idx, area, min, max;
  double mean;
  while (inf >> idx >> area >> mean >> min >> max) {
    if (inf.eof()) break;
    std::cout << idx << " " << area << " " << mean << " " << min << " " << max << std::endl;
  }
  return 0;
}

是:

1)易于阅读。

2)更少的代码,因此错误的机会更少。

3)EOF的正确处理。

尽管我已经离开了第一行,但这取决于您。

fscanf返回读取的参数数。因此,如果返回少于5,则应退出循环。

op最终使用operator>>,这是在C 中执行此操作的正确方法。但是,对于有兴趣的C读取器而言,已发布的代码中有几个问题:

  • mean被声明为double,但使用错误的格式指定器%f而不是%lf
  • 第一行尚未完全读取,而是第一个令牌Area

实施所需任务的可能方法如下:

r = fscanf(datafile,"%[^n]n",skip);
//                    ^^^^^ read till newline
while ( (r = fscanf(datafile,"%d%d%lf%d%d",&index,&area,&mean,&min,&max)) == 5 ) {
    //                             ^^ correct format specifier for double
    // ...
}