Writing std::string to std::ofstream

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
What do you mean by "not allow"? Does it not compile? Does it crash? Does it blow up your computer?
using: outputStream << myString results in a compilation error.
I don't believe you. Please copy and paste the exact error message.
have you included the <string> header?
That's because there is no overload for strings. You have to convert it to a c-string:
outputStream << myString.c_str();
Horscht wrote:
That's because there is no overload for strings. You have to convert it to a c-string
This is not true.
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.
You should never rely on that. Always include the headers for the things you use.
Topic archived. No new replies allowed.