Hi! I am trying to use ofstream. All of the examples I have seen online construct the stream like this:
What I would like to do is to create a function that takes a string as an input, something like this:
However, I get an error because file_name is not the correct type. I did some searching without much luck. I would appreciate some feedback about how to fix this problem. Thank you!
int write_stuff_to_a_file(string file_name)
You can get a c-style string representation of a C++ string object with c_str().
The constructor for the C++ streams take a C-string, unless you are using a C++11 compiler. So you will need to use the string.c_str() member function to open your stream. Also remember if you declare your ofstream inside an if statement it will only be in the scope of the if statement. You may consider creating an instance before your if statement and opening it in the if.
Thank you both! Why does c++ use c style strings. For backward compatibility?
AFAIK (From the C++ Annotations book)
Originally Posted by aaleclaire
When the first C++ standard was being made, the iostream and string libraries were made parallelly, each group without knowledge of the other's work, so ofstream and some others take a C style string as the argument.
Though, from C++11 this is no longer the case, as you can use std::string `s for that purpose, as Jim said.