Make section 2.5 of ROOT Primer more pedagogically clear

Hi,

I would edit this and submit a diff patch, but I’m not sure how to do that for something like the primer. For this snipped of code:

root[1] TH1F* h = new TH1F("h","example histogram",100,0.,5.); root[2] ifstream inp; double x; root[3] inp.open("expo.DAT"); root[4] while(!(inp >> x)==0){h->Fill(x);} root[5] h->Draw(); root[6] inp.close();

The handling of the ifstream is very confusing, the while loop is
almost impossible to parse without major dissection, and its very
hackish. Since this primer is targeted at a quickstart for students,
I think it may be better to write it as:

root[1] TH1F* h = new TH1F("h","example histogram",100,0.,5.); root[2] ifstream inp; double x; root[3] inp.open("expo.DAT"); root[4] while(inp.good()){inp >> x; h->Fill(x);} root[5] h->Draw(); root[6] inp.close();

Another thing that may help is if the preceding paragraph is forced
onto the next page so that the explanation of the snippet is easier to
find.

What you propose:
root[4] while(inp.good()){inp >> x; h->Fill(x);}
is incorrect (you should check “inp.good()” AFTER you “inp >> x;”, not before it).

The current implementation is very close to the idiomatic version

while (inp >> x) {
    h->Fill(x);
}

Yes, the simplest way could be:
while (inp >> x) h->Fill(x);
Actually, I don’t understand why they use “!(inp >> x)==0”.

It might be to support prehistoric compilers or interpreters which didn’t support bool types, but it is still more complicated than the typical workaround I am aware of: while(!!(inp >> x)) { }. Also definitely not an approach beginners should be taught today.

You should make a diff (against the git repository). The doc files you need to modify (in the markdown format)
in the trunk version of ROOT: $ROOTSYS/docbook/primer/*.md

Hi,

before somebody suggests something complicated I am attaching a patch implementing the idiomatic version. This should apply cleanly with git am some_patch.C on the tip of master (and it would be great if filenames ending in .patch weren’t banned on this board).
0001-Use-more-idiomatic-way-to-read-from-file_patch.C (871 Bytes)

patch applied.

Sorry, I have to admit I didn’t even try to run that code. In the current form (while(inp>>x){…}) is much easier to parse by eye than the previous one. Thanks for telling me how to submit patches for the future, even if I didn’t get this one done.

Cheers,

 Dave