如何将函数的输出数据存储在文本文件中

How to store output data of a function in a text file

我有以下代码

    if (StartMonitor) //StartMonitor
    {

        TotalVoltage5s += CalculatePower();
        //TotalVoltage5s += 20;
        xx123++;

        CString sad;
        m_power_edit.GetWindowText(sad);

        int num1 = _ttoi(sad);
        if(xx123 >= num1){
            if(TotalTime > 19){

                Power_Log_Chart.ClearChart();
                TotalTime = 0;
            }



            CTime tm;
            tm=CTime::GetCurrentTime();
            CString str=tm.Format("%X");
            ostringstream os;
            ostringstream os1;
            float ds= (float)atof((char *)(LPTSTR)(LPCTSTR)sad);
            os << TotalVoltage5s/ds;
            os1 << m_frequency;
            m_power_list.InsertColumn(Current_columns,"",LVCFMT_CENTER,80,0);
            m_power_list.SetItemText(0, Current_columns, str);
            m_power_list.SetItemText(1, Current_columns, os.str().c_str());
            m_power_list.SetItemText(2, Current_columns, os1.str().c_str());
            m_power_list.SetItemState(Current_columns, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);  
            m_power_list.EnsureVisible(Current_columns, FALSE);

            Power_Log_Chart.SetXYValue(TotalTime, TotalVoltage5s/ds, TotalTime, 0);
            TotalTime++;
            TotalVoltage5s = 0;
            m_frequency = 0; 
            xx123 = 0;

        }

    }
    Power_Log_Chart.Invalidate();
}
CDialog::OnTimer(nIDEvent);

}

它所做的只是获取函数 CalculatePower 的输出,并每 5 秒实时绘制和显示其结果,它对频率和时间做同样的事情。

我需要一种将数据保存在文本文件中的方法,这就是我尝试做的,但我不确定它是否有效。

        SavePowerData[32780] =TotalVoltage5s; 
        SaveTimeData[32780] = TotalTime; 
         ofstream myfile;
         myfile.open ("Power Data.txt");
        for(int x=0; x<=TotalVoltage5s; x++)
        {
         myfile << SavePowerData[x];
         myfile << SaveTimeData[x]; 
        }
        myfile.close();
#include <fstream>

void append_file(std::string param1,std::string param2, std::string param3){  
  std::ofstream outfile;

  outfile.open("out.txt", std::ios_base::app);
  outfile << param1 << " " << param2<< " " << param3; 
}

您可以尝试像这样封装您的方法,并在将它们放入您的绘图之前每次将您想要的值附加到文件中。您还可以在每 3 个参数的末尾后使用分隔符,这样以后阅读起来会更容易。

谢谢 Yigit,这就是我所做的并且有效,

for (int q = 0; q<=TotalTime; q++)
{ 
Time_[q] = TotalTime;  
voltage[q] = TotalVoltage5s;
Frequency[q] = m_frequency;}
std::ofstream outfile;
 outfile.open("Power Data.csv", std::ios_base::app);
outfile<<"Total Time"<<"   "<<"Total Voltage 5 sec"<<"   "<<"Frequency"<<endl; 
for(int k = 0; k<TotalTime; k++){outfile<<voltage[k]<<", "<<Time_[k]<<", "<<Frequency[k]<<endl;} 
outfile.close();