使用FSCANF从ints和floats中读取C 中的浮子
Using fscanf to read from tabbed file with ints and floats in C++
我已经在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
// ...
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在c++中从文本文件中逐行读取整数
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 独立读取-修改-写入顺序
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 使用FSCANF从ints和floats中读取C 中的浮子
- 从文本文件中读取Floats直到超出ifstream作用域c++