簡體   English   中英

如何將 C++ 中的循環 output 保存到包含列和行的 a.txt 文件

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

我是 C++ 新手,我想保存在循環多個文件時打印的輸出。 輸出是 3 個浮點數,稱為mass_polesumsum_SM 如何使用正確的 C++ 選項卡/新行語義將這些循環輸出(不覆蓋它們)保存到 a.txt 文件。 我想要類似的東西:

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

在 a.txt 文件中(沒有標題)。

到目前為止,我的代碼如下,但我認為這不符合我上述的願望。 具體來說,我需要 L25 以后的幫助。 任何建議將不勝感激!

// 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;
  }
}

根據評論部分所有專家的幫助,這是最終有效的代碼:

  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";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM