Dan
Dan

Reputation: 35443

Opening a file with std::string

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?

Upvotes: 2

Views: 2419

Answers (3)

Assaf Lavie
Assaf Lavie

Reputation: 75983

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.

Upvotes: 0

crashmstr
crashmstr

Reputation: 28573

this should work:

output.open(path.c_str())

Upvotes: 2

G S
G S

Reputation: 36838

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());

Upvotes: 9

Related Questions