Search code examples
c++visual-c++-6

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


I have the following code

    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);

}

What it simply does, it takes the output of the function CalculatePower and it plots and displays its results in real time every 5 seconds, and it does the same thing for frequency and time.

I need a method to save the data in a text file and this is what i tried to do but i am not sure if it is going to work or not.

        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();

Solution

  • #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; 
    }
    

    You can try to encapsulate your method like this and append the values you want to the file each time before putting them to your plot. You can also use a separator just after the end of each 3 params so it will be easier to read from afterwards.