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?

Recommended Answers

All 2 Replies

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.

commented: Good explanation.. Thanks +3

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.