C++ 如何将 std::string 转换为 LPCSTR?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1200188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert std::string to LPCSTR?
提问by Cute
How can I convert a std::stringto LPCSTR? Also, how can I convert a std::stringto LPWSTR?
如何将 a 转换std::string为LPCSTR?另外,如何将 a 转换std::string为LPWSTR?
I am totally confused with these LPCSTRLPSTRLPWSTRand LPCWSTR.
我对这些LPCSTRLPSTRLPWSTR和LPCWSTR.
Are LPWSTRand LPCWSTRthe same?
是LPWSTR和LPCWSTR一样吗?
回答by Nick Meyer
Call c_str()to get a const char *(LPCSTR) from a std::string.
调用c_str()以从 a 中获取const char *( LPCSTR) std::string。
It's all in the name:
这一切都在名称中:
LPSTR- (long) pointer to string - char *
LPSTR- (长)指向字符串的指针 - char *
LPCSTR- (long) pointer to constant string - const char *
LPCSTR- (长)指向常量字符串的指针 - const char *
LPWSTR- (long) pointer to Unicode (wide) string - wchar_t *
LPWSTR-(长)指向 Unicode(宽)字符串的指针 - wchar_t *
LPCWSTR- (long) pointer to constant Unicode (wide) string - const wchar_t *
LPCWSTR-(长)指向常量 Unicode(宽)字符串的指针 - const wchar_t *
LPTSTR- (long) pointer to TCHAR (Unicode if UNICODE is defined, ANSI if not) string - TCHAR *
LPTSTR-(长)指向 TCHAR 的指针(如果定义了 UNICODE,则为 Unicode,否则为 ANSI)字符串 - TCHAR *
LPCTSTR- (long) pointer to constant TCHAR string - const TCHAR *
LPCTSTR-(长)指向常量 TCHAR 字符串的指针 - const TCHAR *
You can ignore the L (long) part of the names -- it's a holdover from 16-bit Windows.
您可以忽略名称的 L(长)部分——它是 16 位 Windows 的保留。
回答by Lou Franco
str.c_str()gives you a const char *, which is an LPCSTR(Long Pointer to Constant STRing) -- means that it's a pointer to a 0terminated string of characters. Wmeans wide string (composed of wchar_tinstead of char).
str.c_str()给你一个const char *,它是一个LPCSTR(指向常量0字符串的长指针)——意味着它是一个指向终止字符串的指针。 W表示宽字符串(由wchar_t而不是组成char)。
回答by CB Bailey
These are Microsoft defined typedefs which correspond to:
这些是 Microsoft 定义的 typedef,它们对应于:
LPCSTR: pointer to null terminated const string of char
LPCSTR:指向空终止常量字符串的指针 char
LPSTR: pointer to null terminated char string of char(often a buffer is passed and used as an 'output' param)
LPSTR:指向空终止字符字符串的指针char(通常传递缓冲区并用作“输出”参数)
LPCWSTR: pointer to null terminated string of const wchar_t
LPCWSTR:指向 const 的空终止字符串的指针 wchar_t
LPWSTR: pointer to null terminated string of wchar_t(often a buffer is passed and used as an 'output' param)
LPWSTR:指向空终止字符串的指针wchar_t(通常传递缓冲区并用作“输出”参数)
To "convert" a std::stringto a LPCSTR depends on the exact context but usually calling .c_str()is sufficient.
将 a 转换std::string为 LPCSTR 取决于确切的上下文,但通常调用.c_str()就足够了。
This works.
这有效。
void TakesString(LPCSTR param);
void f(const std::string& param)
{
TakesString(param.c_str());
}
Note that you shouldn't attempt to do something like this.
请注意,您不应该尝试做这样的事情。
LPCSTR GetString()
{
std::string tmp("temporary");
return tmp.c_str();
}
The buffer returned by .c_str()is owned by the std::stringinstance and will only be valid until the string is next modified or destroyed.
返回的缓冲区.c_str()归std::string实例所有,并且仅在下一次修改或销毁字符串之前有效。
To convert a std::stringto a LPWSTRis more complicated. Wanting an LPWSTRimplies that you need a modifiable buffer and you also need to be sure that you understand what character encodingthe std::stringis using. If the std::stringcontains a string using the system default encoding (assuming windows, here), then you can find the length of the required wide character buffer and perform the transcoding using MultiByteToWideChar(a Win32 API function).
将 a 转换std::string为 aLPWSTR比较复杂。婉婷的LPWSTR暗示,你需要修改的缓冲区,你还需要确保你明白什么字符编码的std::string使用。如果std::string包含使用系统默认编码的字符串(假设是windows,这里),那么您可以找到所需的宽字符缓冲区的长度并使用MultiByteToWideChar(Win32 API 函数)执行转码。
e.g.
例如
void f(const std:string& instr)
{
// Assumes std::string is encoded in the current Windows ANSI codepage
int bufferlen = ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), NULL, 0);
if (bufferlen == 0)
{
// Something went wrong. Perhaps, check GetLastError() and log.
return;
}
// Allocate new LPWSTR - must deallocate it later
LPWSTR widestr = new WCHAR[bufferlen + 1];
::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), widestr, bufferlen);
// Ensure wide string is null terminated
widestr[bufferlen] = 0;
// Do something with widestr
delete[] widestr;
}
回答by Kirill V. Lyadvinsky
Using LPWSTRyou could change contents of string where it points to. Using LPCWSTRyou couldn't change contents of string where it points to.
使用LPWSTR您可以更改它指向的字符串的内容。使用LPCWSTR你不能改变它指向的字符串的内容。
std::string s = SOME_STRING;
// get temporary LPSTR (not really safe)
LPSTR pst = &s[0];
// get temporary LPCSTR (pretty safe)
LPCSTR pcstr = s.c_str();
// convert to std::wstring
std::wstring ws;
ws.assign( s.begin(), s.end() );
// get temporary LPWSTR (not really safe)
LPWSTR pwst = &ws[0];
// get temporary LPCWSTR (pretty safe)
LPCWSTR pcwstr = ws.c_str();
LPWSTRis just a pointer to original string. You shouldn't return it from function using the sample above. To get not temporary LPWSTRyou should made a copy of original string on the heap. Check the sample below:
LPWSTR只是一个指向原始字符串的指针。您不应该使用上面的示例从函数中返回它。为了不是临时的,LPWSTR您应该在堆上复制原始字符串。检查下面的示例:
LPWSTR ConvertToLPWSTR( const std::string& s )
{
LPWSTR ws = new wchar_t[s.size()+1]; // +1 for zero at the end
copy( s.begin(), s.end(), ws );
ws[s.size()] = 0; // zero at the end
return ws;
}
void f()
{
std::string s = SOME_STRING;
LPWSTR ws = ConvertToLPWSTR( s );
// some actions
delete[] ws; // caller responsible for deletion
}
回答by Joel
The MultiByteToWideCharanswer that Charles Bailey gave is the correct one. Because LPCWSTRis just a typedef for const WCHAR*, widestrin the example code there can be used wherever a LPWSTRis expected or where a LPCWSTRis expected.
MultiByteToWideCharCharles Bailey 给出的答案是正确的。因为LPCWSTR只是 for 的 typedef const WCHAR*,widestr在示例代码中,可以在LPWSTR预期 a 或LPCWSTR预期a 的任何地方使用。
One minor tweak would be to use std::vector<WCHAR>instead of a manually managed array:
一个小的调整是使用std::vector<WCHAR>而不是手动管理的数组:
// using vector, buffer is deallocated when function ends
std::vector<WCHAR> widestr(bufferlen + 1);
::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), &widestr[0], bufferlen);
// Ensure wide string is null terminated
widestr[bufferlen] = 0;
// no need to delete; handled by vector
Also, if you need to work with wide strings to start with, you can use std::wstringinstead of std::string. If you want to work with the Windows TCHARtype, you can use std::basic_string<TCHAR>. Converting from std::wstringto LPCWSTRor from std::basic_string<TCHAR>to LPCTSTRis just a matter of calling c_str. It's when you're changing between ANSI and UTF-16 characters that MultiByteToWideChar(and its inverse WideCharToMultiByte) comes into the picture.
此外,如果您需要使用宽字符串开始,您可以使用std::wstring代替std::string. 如果要使用 WindowsTCHAR类型,可以使用std::basic_string<TCHAR>. 从std::wstringtoLPCWSTR或 from std::basic_string<TCHAR>to转换LPCTSTR只是调用c_str. 当您在 ANSI 和 UTF-16 字符之间进行更改时MultiByteToWideChar(及其反字符WideCharToMultiByte)就会出现。
回答by Timbo
The conversion is simple:
转换很简单:
std::string str; LPCSTR lpcstr = str.c_str();
std::string str; LPCSTR lpcstr = str.c_str();
回答by Nick Haddad
Converting is simple:
转换很简单:
std::string myString;
LPCSTR lpMyString = myString.c_str();
One thing to be careful of here is that c_str does not return a copy of myString, but just a pointer to the character string that std::string wraps. If you want/need a copy you'll need to make one yourself using strcpy.
这里要注意的一件事是 c_str 不返回 myString 的副本,而只是一个指向 std::string 包装的字符串的指针。如果您想要/需要一份副本,则需要使用 strcpy 自己制作一份。
回答by MSalters
The easiest way to convert a std::stringto a LPWSTRis in my opinion:
我认为将 a 转换std::string为 a的最简单方法LPWSTR是:
- Convert the
std::stringto astd::vector<wchar_t> - Take the address of the first
wchar_tin the vector.
- 转换
std::string为std::vector<wchar_t> wchar_t取向量中第一个的地址。
std::vector<wchar_t>has a templated ctor which will take two iterators, such as the std::string.begin()and .end()iterators. This will convert each char to a wchar_t, though. That's only valid if the std::stringcontains ASCII or Latin-1, due to the way Unicode values resemble Latin-1 values. If it contains CP1252 or characters from any other encoding, it's more complicated. You'll then need to convert the characters.
std::vector<wchar_t>有一个模板化的 ctor,它将采用两个迭代器,例如std::string.begin()和.end()迭代器。不过,这会将每个字符转换为 a wchar_t。std::string由于 Unicode 值类似于 Latin-1 值的方式,这仅在包含 ASCII 或 Latin-1 时有效。如果它包含 CP1252 或来自任何其他编码的字符,则更复杂。然后,您需要转换字符。
回答by Nani
std::string myString("SomeValue");
LPSTR lpSTR = const_cast<char*>(myString.c_str());
myStringis the input string and lpSTRis it's LPSTRequivalent.
myString是输入字符串,lpSTR是它的LPSTR等价物。

