我正在尝试将TCHAR转换为字符串,如下所示:
std::string mypath;
TCHAR path[MAX_PATH];
GetModuleFileName( NULL, path, MAX_PATH );
Run Code Online (Sandbox Code Playgroud)
我需要设置mypath到的path.我做了一个简单的循环并连接path[index]到了mypath,这有效,但我不喜欢这种方式.
我是C++的新手,但已经做了很多C#.我已经看过GetModuleFileName传入"char"的例子,但它不喜欢它.它需要TCHAR或者a LPWSTR.
rer*_*run 22
TCHAR是一个定义为char或wchar的宏,具体取决于您定义的字符集.2008之后的默认值是将字符设置为unicode.如果您更改字符集,此代码将起作用.
int _tmain(int argc, _TCHAR* argv[])
{
TCHAR* bob ="hi";
string s = bob;
}
Run Code Online (Sandbox Code Playgroud)
右键单击项目设置并查看下面的内容

如果要将TCHAR用作Unicode字符集,请使用wstring
Oha*_*adM 10
当我真的需要这样做时,我使用以下内容:
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.
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
如果你想要chars中的路径,你应该打电话GetModuleFilenameA.该功能LPSTR取而代之LPTSTR.
请注意,几乎所有采用或返回字符串的Win32函数都有两个版本,一个以A(ANSI?)结尾,另一个以W(wide)结尾.
您也可以转换_TCHAR*为char*使用wcstombs或wcstombs_s功能
http://msdn.microsoft.com/en-us/library/5d7tc9zw%28v=vs.80%29.aspx