my goal is to read in a data file consisting of just one number per line and write the data into a histogram. There are some comments in the file behind #
characters. I want to skip these lines.
I have started writing:
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);
}
But only every other line gets written as "line" while the others are fscanfed.
Would be very nice, if someone could give me a hint.
...so this will obviously not work properly:
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);
}
}
You need to use
sscanf()
instead offscanf()
after you've read the line withfgets()
:I left the
sprintf()
for the file name in place, but it provides marginal value. I'd be tempted to useconst char *filename = "test.dat";
so that the error message can report the file name that failed to open without repeating the string literal.Converted into a standalone test program:
and given a test data file
test.dat
containing:the output from the program shown is:
This generates the three expected
val
lines and reads but ignores the two comment lines.