简体   繁体   English

std :: ostringstream到LPCSTR?

[英]std::ostringstream to LPCSTR?

How can I convert a std::ostringstream to LPCSTR ? 如何将std::ostringstream转换为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 结果: Error: No suitable conversion function from "std::basic_string<char, std::char_traits<char>, std::allocator<char>>" to "LPCSTR" exists

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 . 请注意,在下一次修改str之前, cstr仅保持有效。 So you cannot, for instance, return cstr from a function because str is a local variable that has left scope. 所以你不能,例如,从函数返回cstr ,因为str是一个已经离开范围的局部变量。

Instead of returning LPCSTR from this function, return std::string . 而不是从此函数返回LPCSTR ,而是返回std::string That avoids dealing with lifetime issues if you returned LPCSTR . 如果您返回LPCSTR这可以避免处理生命周期问题。 If you returned LPCSTR you would have to allocate memory and make sure you deallocated it. 如果您返回LPCSTR ,则必须分配内存并确保已取消分配。 Exactly the sort of thing you don't want to be doing in C++ code. 确实是你不想在C ++代码中做的事情。 So, return std::string and call c_str() on that object at the point where you call the Windows API function. 因此,返回std::string并在您调用Windows API函数的位置调用该对象上的c_str()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM