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
Like this:
Note that you
cstr
only remains valid until the next modification ofstr
. So you cannot, for instance, returncstr
from a function becausestr
is a local variable that has left scope.Instead of returning
LPCSTR
from this function, returnstd::string
. That avoids dealing with lifetime issues if you returnedLPCSTR
. If you returnedLPCSTR
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, returnstd::string
and callc_str()
on that object at the point where you call the Windows API function.