在 C++ 中将 TCHAR 转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6006319/
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
Converting TCHAR to string in C++
提问by David
I'm trying to convert a TCHAR to a string as in:
我正在尝试将 TCHAR 转换为字符串,如下所示:
std::string mypath;
TCHAR path[MAX_PATH];
GetModuleFileName( NULL, path, MAX_PATH );
I need to set mypath
to that of path
. I did a simple loop and concatenated path[index]
to mypath
and this works but I don't like this way.
我需要设置mypath
为path
. 我做了一个简单的循环并连接path[index]
到mypath
,这有效,但我不喜欢这种方式。
I'm new to C++ but have done plenty of C#. I've seen examples of the GetModuleFileName
that passes in a "char" but it doesn't like it. It needs the TCHAR
or a LPWSTR
.
我是 C++ 的新手,但已经完成了大量的 C#。我见过GetModuleFileName
传递“字符”的例子,但它不喜欢它。它需要TCHAR
或LPWSTR
。
回答by rerun
TCHAR is a macro defined as a char or wchar depending on what you have your character set defined to. The default after 2008 is have the character set to unicode. this code works if you change your character set.
TCHAR 是一个定义为 char 或 wchar 的宏,具体取决于您定义的字符集。2008 年之后的默认设置是将字符设置为 unicode。如果您更改字符集,则此代码有效。
int _tmain(int argc, _TCHAR* argv[])
{
TCHAR* bob ="hi";
string s = bob;
}
Right click on the project settings and chage the folowing
右键单击项目设置并更改以下内容
if You want to use TCHAR as a Unicode character set use wstring
如果要将 TCHAR 用作 Unicode 字符集,请使用wstring
回答by OhadM
When I reallyneed to do it I use the following:
当我真的需要这样做时,我使用以下方法:
TCHAR infoBuf[32767]
GetWindowsDirectory(infoBuf, 32767);
//Let's convert to string...
wstring test(&infoBuf[0]); //convert to wstring
string test2(test.begin(), test.end()); //and convert to string.
Hope that helps.
希望有帮助。
回答by avakar
If you want the path in chars, you should call GetModuleFilenameA
. That function takes LPSTR
instead of LPTSTR
.
如果您想要字符中的路径,您应该调用GetModuleFilenameA
. 该函数采用LPSTR
代替LPTSTR
.
Note that almost all Win32 functions that take or return strings have two version, one ending in A
(ANSI?) and the other ending in W
(wide).
请注意,几乎所有接受或返回字符串的 Win32 函数都有两个版本,一个以A
(ANSI?) 结尾,另一个以W
(wide)结尾。
回答by nuoritoveri
You can also convert from _TCHAR*
to char*
using wcstombs
or wcstombs_s
function
您还可以从转换_TCHAR*
为char*
usingwcstombs
或wcstombs_s
function
http://msdn.microsoft.com/en-us/library/5d7tc9zw%28v=vs.80%29.aspx
http://msdn.microsoft.com/en-us/library/5d7tc9zw%28v=vs.80%29.aspx