Tom Doodler
Tom Doodler

Reputation: 1559

std::ostringstream to LPCSTR?

How can I convert a std::ostringstream to LPCSTR?

std::ostringstream oss;
[...]
LPCSTR result = oss.str();

Result: Error: No suitable conversion function from "std::basic_string<char, std::char_traits<char>, std::allocator<char>>" to "LPCSTR" exists

Upvotes: 3

Views: 2727

Answers (1)

David Heffernan
David Heffernan

Reputation: 612794

Like this:

std::string str = oss.str();
LPCSTR cstr = str.c_str();

Note that you cstr only remains valid until the next modification of str. So you cannot, for instance, return cstr from a function because str is a local variable that has left scope.

Instead of returning LPCSTR from this function, return std::string. That avoids dealing with lifetime issues if you returned LPCSTR. If you returned LPCSTR you would have to allocate memory and make sure you deallocated it. Exactly the sort of thing you don't want to be doing in C++ code. So, return std::string and call c_str() on that object at the point where you call the Windows API function.

Upvotes: 8

Related Questions