我的目标是读取每行只包含一个数字的数据文件,并将数据写入直方图。 #
个字符后面的文件中有一些注释。我想跳过这些界限。
我已经开始写作了:
TH1F *hist = new TH1F("hist","",4096, -0.5,4095.5);
//TF1 *fitfunc;
char filename[100];
double val;
int i;
char line[256];
sprintf(filename,"test.dat");
FILE* pfile = fopen(filename, "r");
for (i=0;i<=14;i++) {
fgets(line,256,pfile);
cout<<line<<endl;
fscanf(pfile, "%lf /n", &val);
hist->SetBinContent(i,val);
}
但是只有其他每一行都被写成“行”,而其他行则是fscanfed。
如果有人能给我一个提示,那将是非常好的。
...所以这显然不会正常工作:
TH1F *hist = new TH1F("hist","",4096, -0.5,4095.5);
//TF1 *fitfunc;
char filename[100];
double val;
int i;
char zeile[256];
sprintf(filename,"test.dat");
FILE* pfile = fopen(filename, "r");
for (i=0;i<=14;i++)
{
fgets(zeile,256,pfile);
cout<<"fgets: "<<zeile<<endl;
if (zeile[0]!='#')
{
fscanf(pfile, "%lf /n", &val);
cout<<"val: "<<val<<endl;
hist->SetBinContent(i,val);
}
}
答案 0 :(得分:1)
在您阅读sscanf()
行之后,您需要使用fscanf()
代替fgets()
:
TH1F *hist = new TH1F("hist", "", 4096, -0.5, 4095.5);
char filename[100];
char zeile[256];
sprintf(filename, "test.dat");
FILE *pfile = fopen(filename, "r");
if (pfile == 0)
…handle error; do not continue…
for (int i = 0; i < 14 && fgets(zeile, sizeof(zeile), pfile) != 0; i++)
{
cout << "fgets: " << zeile << endl;
if (zeile[0] != '#')
{
double val;
if (sscanf(zeile, "%lf", &val) == 1)
{
cout << "val: " << val << endl;
hist->SetBinContent(i, val);
}
// else … optionally report that line was erroneous
}
}
我将sprintf()
留给了文件名,但它提供了边际值。我很想使用const char *filename = "test.dat";
,以便错误消息可以报告无法打开的文件名而不重复字符串文字。
转换为独立的测试程序:
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
char filename[100];
char zeile[256];
sprintf(filename, "test.dat");
FILE *pfile = fopen(filename, "r");
if (pfile != 0)
{
for (int i = 0; i < 14 && fgets(zeile, sizeof(zeile), pfile) != 0; i++)
{
cout << "fgets: " << zeile;
if (zeile[0] != '#')
{
double val;
if (sscanf(zeile, "%lf", &val) == 1)
cout << "val: " << val << endl;
}
}
fclose(pfile);
}
return 0;
}
并给出包含以下内容的测试数据文件test.dat
1.234
2.345
#3.456
#4.567
5.678
显示的程序输出为:
fgets: 1.234
val: 1.234
fgets: 2.345
val: 2.345
fgets: #3.456
fgets: #4.567
fgets: 5.678
val: 5.678
这将生成三个预期的val
行并读取但忽略两个注释行。