简体   繁体   中英

How to save looped output in C++ to a .txt file with columns and rows

I'm a C++ newbie and am wanting to save outputs that are printed when looping over several files. The outputs are 3 floats, which are called mass_pole , sum , and sum_SM . How do I save these looped outputs (without overwriting them) to a.txt file using the proper C++ tabs / new line semantics. I'm wanting something like:

//mass_pole    //sum        //sum_SM
200            2300.2       713.4
250            2517.3       1231.77
300            2110.5       432.5

inside a.txt file (without the headers).

My code so far is below, but I don't think this is correct for my aforementioned desire. Specifically, I need help with L25 onward. Any advice would be much appreciated!

// root -l aTGCs_test.C                                                                                                                                                                         
#include <iostream>
#include <fstream>
#include <string>
#include "TMath.h"

using namespace std;


void masspoleweights(TString file, TString mass_pole) {

  TChain* myTrees = new TChain("Events");

 [. . .]

  for (int j = 0; j < myTrees->GetEntries(); ++j){
  //for (int j = 0; j < 1000; ++j){                                                                                                                                                             
    myTrees->GetEntry(j);

    sum=variable1;
    sum_SM=variable2;

  }

L25>>  ofstream myfile ("weights.txt");

  //saving outputs to file (three outputs that loop by mass: mass, sum, pdfweights)

  for (int i = 0; i < 200; ++i){
    myfile << mass_pole << sum << sum_SM << std::endl;
  }
}

As per the help of all the experts in the comments section, here is the final code that works:

  ofstream myfile ("weights.txt", ios::in | ios::out | ios::app); //file open mode (READ), WRITE, append                                                                                                                      

  //loop over all outputs to save in a txt file (no overwrites):                                                                      
  for (int i = 0; i < 1; ++i){
    ofstream::ios_base::app;
    myfile << mass_pole << "\t"  << sum << "\t" << sum_SM << "\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM