file opening newbie question

Hi all

I am a C++ newbie and this is my first post to the forum. I will begin with saying that this site is awesome and I have been using the examples to gain better understanding of the language.

I am running some simulations in C++ and I need to store data to the disc intermittently. e.g., for Run 1, I need to save data in File_1.txt

I am able to generate a string "File_1.txt" (by converting integer 1 to string 1), however the following piece of code is giving error

1
2
3
ofstream myfile;
string filename = "File_1.txt";
myfile.open(filename);


Is there a workaround this, since the filename will change in each run to File_2.txt, File_3.txt etc;

Thanks
Ayesha
I forgot to give the error I received

simulation_file.cpp: In function 'int main()':
simulation_file.cpp:16: error: no matching function for call to 'std::basic_ofstream<char, std::char_traits<char> >::open(std::string&)'
/usr/include/c++/4.0.0/fstream:628: note: candidates are: void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]


Ayesha
 
char filename[] = "File_1.txt";

instead of
 
string filename = "File_1.txt";


worked !

ayesha
Last edited on
The problem is not solved yet, I jumped the gun I guess..

I have string filename = "File_1.txt";

how do I convert it to char filename[] = "File_1.txt" ; ?

Any help is welcome. Thanks!
You can use the following:
myfile.open(filename.c_str());

c_str(), a member function of the string type, converts a string to a C-style string (character array), which is what the open() function is looking for.
Last edited on
That worked! Thanks rpgfan3233
rpgfan3233,
I needed that as well. Thank you,
Last edited on
Topic archived. No new replies allowed.