gpt4 book ai didi

c++ - 在 C++ 中使用 fscanf 读取带有 int 和 float 的选项卡式文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:13:04 26 4
gpt4 key购买 nike

我在 StackOverflow 和其他网站上找了一天左右,但找不到解决我的问题的方法。有一些是相似的,但我似乎无法让它们工作。

我有一个制表符分隔的 .txt 文件。一行包含一个标题,之后的 500 行依次包含一个整数、一个整数、一个 float 、一个整数和一个整数。我有一个函数应该从每一行读取第一个和第三个值(第一个整数和 float )。它跳过第一行。这是一个 do-while 循环,因为我需要能够处理不同长度的文件。但是,它陷入了循环。我将其设置为输出均值,但它只会永远输出零。

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,"%s\n",skip);
cout << skip << endl; //just to check

//this is the problematic code
do {
r = fscanf(datafile,"%d\t%d\t%f\t%d\t%d\n",&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

谢谢!

编辑:我说过我需要读取第一个和第三个值,而且我知道我正在读取所有这些值。最终我需要存储第一个和第三个值,但为了简洁起见我删掉了那部分。并不是说这个评论很简短。

最佳答案

你应该用 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

虽然我已经离开了第一行的处理,但这取决于你。

关于c++ - 在 C++ 中使用 fscanf 读取带有 int 和 float 的选项卡式文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37815549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com