Reading & Writing Data
Table of Contents
Writing Data
TRandom2 *r = new TRandom2();Now we want to open our output file "output.txt" by using ofstream which comes along with C++:
ofstream outfile; outfile.open("output.txt");At the end of our macro, we have to close the file by writing
outfile.close();Between these lines we have to create the random data with the following for loop:
for(int i = 0; i < 1000; i++) { outfile << r->Rndm()*10 << endl; }The important member function used for generating random numbers between 0 and 1 is called Rndm(). Due to multiplication with 10, the created random numbers are positioned between 0 and 10. The full code looks now as follows:
void write() { TRandom2 *r = new TRandom2(); ofstream outfile; outfile.open("output.txt"); for(int i = 0; i < 1000; i++) { outfile << r->Rndm()*10 << endl; } outfile.close(); }If you run the code now, then it creates an output file with the given file name.
Reading Data
ifstream infile; infile.open("output.txt");And of course we also have to close it at the end:
infile.close();We also want to create a histogram with 100 bins from 0 to 100:
TH1F *hist = new TH1F("hist", "Histogram", 100, 0, 10);Now the main code has to be wrapped by a while loop:
while(1) { double value; infile >> value; if(infile.eof()) break; hist->Fill(value); }Here, an infinite while loop runs over all entries of the input file. As soon as the end of the file is reached (the function eof() stands for "end of file"), the loop breaks and the script continues to be executed. Every value, that is read out from the input file, will automatically be filled into the defined histogram. Now finally we only have to create a canvas and draw the histogram. The full code looks as follows:
void read() { ifstream infile; infile.open("output.txt"); TH1F *hist = new TH1F("hist", "Histogram", 100, 0, 10); while(1) { double value; infile >> value; if(infile.eof()) break; hist->Fill(value); } infile.close(); TCanvas *c1 = new TCanvas(); hist->Draw(); }If you run this skript, you will find a histogram with many entries between the defined values 0 and 10. You can repeat the same procedure with changing the number of created random numbers or the histogram properties, such as the binning or the limits.
This page contains 540 words and 3481 characters.
Last modified: 2022-10-08 21:05:16 by mustafa