在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:19:28  来源:igfitidea点击:

Converting TCHAR to string in C++

c++tchar

提问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 mypathto that of path. I did a simple loop and concatenated path[index]to mypathand this works but I don't like this way.

我需要设置mypathpath. 我做了一个简单的循环并连接path[index]mypath,这有效,但我不喜欢这种方式。

I'm new to C++ but have done plenty of C#. I've seen examples of the GetModuleFileNamethat passes in a "char" but it doesn't like it. It needs the TCHARor a LPWSTR.

我是 C++ 的新手,但已经完成了大量的 C#。我见过GetModuleFileName传递“字符”的例子,但它不喜欢它。它需要TCHARLPWSTR

回答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

右键单击项目设置并更改以下内容

enter image description here

在此处输入图片说明

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 LPSTRinstead 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 wcstombsor wcstombs_sfunction

您还可以从转换_TCHAR*char*usingwcstombswcstombs_sfunction

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