ofstream Odeint输出到txt文件

时间:2016-02-16 06:14:37

标签: c++ ofstream odeint

我尝试从ODEINT库运行此示例来解决ODE。它只是运行正常,但不是cout结果屏幕,我想将它们写入文件。我将此ofstream添加到write_cout函数下的代码中,但它只将结果的最后一行写入文件而不是全部。 你对此有什么想法吗?感谢

#include <iostream>
#include <boost/numeric/odeint.hpp>
#include <fstream>

using namespace std;
using namespace boost::numeric::odeint;


void rhs( const double x , double &dxdt , const double t )
{
dxdt = 3.0/(2.0*t*t) + x/(2.0*t);
}

void write_cout( const double &x , const double t )
{
cout << t << '\t' << x << endl;
cout<<"alo"<<endl;

ofstream buckyFile ("tuna.txt");
buckyFile<<t <<'\t'<<x<<endl;

}

// state_type = double
typedef runge_kutta_dopri5< double > stepper_type;

int main()
{
double x = 0.0;
integrate_adaptive( make_controlled( 1E-12 , 1E-12 , stepper_type() ) ,
                    rhs , x , 1.0 , 10.0 , 0.1 , write_cout );
}

2 个答案:

答案 0 :(得分:1)

甚至更好

struct stream_writer
{
    std::ostream& m_out;
    stream_writer( std::ostream& out ) : m_out( out ) {}
    void operator()( const double &x , const double t )
    {
        m_out << t << "\t" << x << "\n";
    }
};

int main()
{
    double x = 0.0;
    ofstream fout( "tuna.txt" ); 
    integrate_adaptive( make_controlled( 1E-12 , 1E-12 , stepper_type() ) ,
                rhs , x , 1.0 , 10.0 , 0.1 , stream_writer( fout ) );
}

答案 1 :(得分:0)

ofstream buckyFile ("tuna.txt");
每次输入函数时,

都会打开一个新文件tuna.txt,覆盖以前的文件。

快速解决方法是使用

static ofstream buckyFile ("tuna.txt");

代替。