写入变量文件名

时间:2015-02-20 17:24:13

标签: c++ filenames fstream ofstream

我想写入名称由变量r给出的不同文件。以下是我写的。这里的问题是,它只是打开第一个文件' r = 0.5.txt'并在其上写入r = 0.5的数据。但是,它不会打开并写入r = 0.6,1.0的其他文件... 编辑:添加了Minimal,Complete和Verifiable示例

#include <iostream>
#include <fstream>

#include <sstream>

using namespace std; 





int main()

{   //initialization
int M = 5; //no. of steps
double rvalues[] = {0.5,1.5,8.,15.,24.5};
double x,y,z,r;
//initial condition fixed pnts x*,y*,z*= (0,0,0)
double x0 =  1.5;
double y0 =  1.5;
double z0 = 1.5; 
ofstream myfile;
for(unsigned int i = 0; i<sizeof(rvalues)/sizeof(rvalues[0]);i++){
    r = rvalues[i];
    x = x0;
    y = y0;
    z=z0;
    stringstream ss;
    cout<<"ravlues = "<<r<<endl;
    ss<<"r="<<r<<".txt";
    string filename = ss.str();
    cout<<filename<<endl;
    myfile.open(filename.c_str());
    for(int j = 0; j<M;j++){
        myfile<<x<<'\t'<<y<<'\t'<<z<<'\n';

        x =x+j;
        y = y+j;
        z = z+j;
    }
}
return 0;

}

1 个答案:

答案 0 :(得分:1)

你忘了在循环结束时拨打myfile.close()。如果在myfile循环的范围内定义for,将会更容易。

for(unsigned int i = 0; i<sizeof(rvalues)/sizeof(rvalues[0]);i++){
    r = rvalues[i];
    x = x0;
    y = y0;
    z=z0;
    stringstream ss;
    cout<<"ravlues = "<<r<<endl;
    ss<<"r="<<r<<".txt";
    string filename = ss.str();
    cout<<filename<<endl;

    ofstream myfile(filename.c_str());  // Move it inside the loop.

    for(int j = 0; j<M;j++){
        myfile<<x<<'\t'<<y<<'\t'<<z<<'\n';

        x =x+j;
        y = y+j;
        z = z+j;
    }
}
相关问题