Writing std::string to std::ofstream

Mar 1, 2015 at 8:15am
Why does my compiler not allow c++ to write a string to the output stream? For example:

1
2
3
4
5
6
7
8
9
10
void foo()
{
    std::ofstream outputStream;
    std::string myString = "x";

    outputStream.open("myFile.txt", ofstream::binary)
    outputStream << myString;

    outputStream.close();
}


Provided that we have a file, its open and we are permitted to write to it.
Last edited on Mar 1, 2015 at 8:18am
Mar 1, 2015 at 8:20am
What do you mean by "not allow"? Does it not compile? Does it crash? Does it blow up your computer?
Mar 1, 2015 at 8:28am
using: outputStream << myString results in a compilation error.
Mar 1, 2015 at 9:09am
I don't believe you. Please copy and paste the exact error message.
Mar 1, 2015 at 9:39am
have you included the <string> header?
Mar 1, 2015 at 11:10am
That's because there is no overload for strings. You have to convert it to a c-string:
outputStream << myString.c_str();
Mar 1, 2015 at 7:53pm
Horscht wrote:
That's because there is no overload for strings. You have to convert it to a c-string
This is not true.
Mar 1, 2015 at 8:05pm
Hmm ok, the overload seems to be in <string>. I looked in the ostream reference.
http://www.cplusplus.com/reference/string/string/operator%3C%3C/
Never knew that, I always converted to c_str() when working with streams.
I thought <string> would be included through some other headers, why else would I be able to use string? But it seems you have to include it additionally.
Mar 1, 2015 at 8:57pm
You should never rely on that. Always include the headers for the things you use.
Topic archived. No new replies allowed.