Writting to file from a function.

I am trying to write data files out of a particle physics simulation that I have built, but I am having trouble trying to make the file name work like I want it to. The problem is the amount of data I have to write, and the number of files I have to write. I want to make a function that I can call, and have write the datafiles, but it needs to put the names for them together itself. Here is an example.

1
2
3
4
            ofstream OutPutFileEvents2;
            string filename;
            filename="DetSim" =+ DetLetter =+ "2MeV.txt";
            OutPutFileEvents2.open (filename);

where DetLetter is an identifier for the data being run through the function that time. DetLetter is from
1
2
3
void DataWrite( vector < vector<double> > DataSetIn, char DetLetter)
{
    int


I understand the the += is not defined for the chars, but if i use strings i get other problems with opening the file. I could really use some help. Thanks
If the problem with strings is that the file opening function only takes c-strings, this is easily solved. You can just do myString.c_str() to return the c-string equivalent of your string, which will be accepted by the file opening function.
Could you give me an example of what you mean?
1
2
3
4
5
6
7
8
9
10
11
12
// necessary includes and stuff

int main()
{
  string fileName = "myFile.txt";
  fstream oFile;
  oFile.open(fileName); //This gives an error in some compilers, as it will not impicitly convert string to c-string

  oFile.open(fileName.c_str()); //This will work, as it explicitly does the necessary conversion  

  return 0;
}
std::string filename = "DetSim" + std::string(1,DetLetter) + "2MeV.txt" ;

Seperate your non-std::strings with a std::string and you should be good.

Alternately:

1
2
3
4
5
6
7
8
std::string buildString( char const* beg, char middle, char const* end )
{
    return (std::string(beg) += middle) += end ;
}

// ...
std::string filename = buildString("DetSim", DetLetter, "2MeV.txt") ;
// ... 
Last edited on
Topic archived. No new replies allowed.