Question

#include <fstream>
#include <iostream>
using namespace std;


int main(){


int value=0;

for (int i=0;i<4;i++)
{
    ofstream myfile("Etc/filename");
    string filename ="key" + i +".txt";
    myfile<<value<<endl;

}
myfile.close();
}

how can i save the file under an etc folder, which has a key1.txt,key2.txt,key3.txt,key4.txt? it seems that i have a problem with ofstream myfile...

Anyone can enlighten of how can i change with it? Thanks!

Was it helpful?

Solution

You need to either pass a correctly formed string as argument to the constructor. For example,

std::ofstream myfile("key" + std::to_string(i) + ".txt"); 

or

#include <sstream> // for std::ostringstream

std::ostringstream strm;
strm << "key" << i << ".txt";
std::ofstream myfile(strm.str());

The above assumes you have a compiler supporting C++11. If you don't, this a slight variation on the second example would work:

std::ofstream myfile(strm.str().c_str());
                                ^^^^^^^
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top