Rene Brun
{
FILE *fp = fopen("foo.txt","r");
Float_t x,y,z;
Int_t ncols;
Int_t nlines = 0;
TNtuple *ntuple = new TNtuple("ntuple","data from ascii
file","x:y:z");
ntuple->SetBranchAddress("x",&x);
ntuple->SetBranchAddress("y",&y);
ntuple->SetBranchAddress("z",&z);
while (1) {
ncols = fscanf(fp,"%f %f %f",&x, &y, &z);
if (ncols < 0) break;
if (nlines < 5) printf("x=%8f, y=%8f, z=%8f\n",x,y,z);
ntuple->Fill();
nlines++;
}
fclose(fp);
// now reading some events
ntuple->GetEvent(3);
//x,y,z should now contain the event 10
printf("x=%f, y=%f, z=%f\n",x,y,z);
}
do not need to setPetar Maksimovic wrote:
>
> Dear Rooters,
>
> this might be a newbie question, but it should be nevertheless interesting
> as an illustration how non-intuitive (and thus non-trivial) some of
> ROOT's features are.
>
> I'm trying to simultaneously fill an ntuple and read from it (in
> another section of the code). One can argue that is perfectly
> reasonable to collect a bunch of events, pause the run, analyze them,
> and then keep on filling the ntuple.
>
> However, it seams that SetBranchAddress() interferes with the Fill()
> method for the variables for which SetBranchAddress() was issued.
> These variables end up being 0.
>
> The example below (which is a slightly modified root tutorial)
> illustrates the point:
>
> {
> FILE *fp = fopen("foo.txt","r");
>
> Float_t x,y,z;
> Float_t x1;
>
> Int_t ncols;
> Int_t nlines = 0;
>
> TNtuple *ntuple = new TNtuple("ntuple","data from ascii file","x:y:z");
>
> // ******************************************************************
> ntuple->SetBranchAddress("x",x1); // <----- why is this dangerous???
> // ******************************************************************
>
> while (1) {
> ncols = fscanf(fp,"%f %f %f",&x, &y, &z);
> if (ncols < 0) break;
> if (nlines < 5) printf("x=%8f, y=%8f, z=%8f\n",x,y,z);
> ntuple->Fill(x,y,z);
> nlines++;
> }
> fclose(fp);
> }
>
> Where the ntuple is read from the file
> % cat foo.txt
> 1 2 3
> 1.1 2.2 3.3
> -1.1 -2.2 -3.3
> -1 -2 -3
> 1.5 1.5 1.5
>
> Here, if the SetBranchAddress() is commented out, everything is fine.
> But once it's uncommented, all "x" entries are 0.0.
>
> My questions:
>
> 1. It's obvious that I'm doing something silly, but for a non-expert
> like me it's hard to pin down the location of this silliness.
>
> 2. If this behavior of TTree is a feature (which it may well be), then what
> is the correct way of doing this?
>
> Many thanks!
>
> Petar