0

I'm trying to use std::ofstream to create a file but I'm getting an error. I'm using a string variable instead of a string. example below.

std::ofstream Myfile("C:\\testfile.html");  // This works fine

//but the below doesn't  

string mystring = "C:\\testfile.html";

std::ofstream Myfile(mystring); //doesn't work. Not sure why.

Any clues?

3
Contributors
2
Replies
15
Views
4 Years
Discussion Span
Last Post by Moschops
1

std::string are different from C-style strings (null terminated sequences of characters).

For your example, use the .c_str() function from the string class to get the C-style string.

std::ofstream Myfile(mystring.c_str());

Click Here to get more info.

Edited by Lucaci Andrew

Votes + Comments
Good explanation.. Thanks
1

Read the error message. They usually give you really good clues as to what the problem is. If you're new to them, they can be a bit tricky to understand, so if you post it, we can walk you through it.

Also, it's helpful to us if you make it clear when your error is a compilation error, and when it compiles and runs and the error happens whilst running.

C++11 will accept a proper C++ string as the constructor parameter for an ofstream object; you might consider looking into updating your compiler so you can take advantage of C++11.

Edited by Moschops

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.