tags:

views:

266

answers:

3

Hi,

This should be a fairly trivial problem. I'm trying to open an ofstream using a std::string (or std::wstring) and having problems getting this to work without a messy conversion.

std::string path = ".../file.txt";

ofstream output;

output.open(path);

Ideally I don't want to have to convert this by hand or involve c-style char pointers if there's a nicer way of doing this?

+9  A: 

In the path string, use two dots instead of three.

Also you may use 'c_str()' method on string to get the underlying C string.

output.open(path.c_str());
Frederick
spot on, thanks.
Dan
+2  A: 

this should work:

output.open(path.c_str())

crashmstr
A: 

I'm afraid it's simply not possible. You have to use c_str, and yes, it sucks.

Incidentally, using char* also means fstream has no support for Unicode file names... a shame.

Assaf Lavie
wfstream for std::wstring anyone?
KTC
No need for a special stream type, just overload open() to take a std::wstring.
KeithB
basic_fstream's constructor accepts _only_ const char * (never wchar_t). See the standard: 27.8.1.6
Assaf Lavie
@Assaf - I know what is in the standard, I was replying to KTC's comment about making another stream class, which doesn't make sense.
KeithB