Converting TCHAR to string in C++

对着背影说爱祢 提交于 2019-12-08 14:37:53

问题


I'm trying to convert a TCHAR to a string as in:

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.

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.


回答1:


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.

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




回答2:


When I really need 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.




回答3:


If you want the path in chars, you should call GetModuleFilenameA. That function takes LPSTR instead of 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).




回答4:


You can also convert from _TCHAR* to char* using wcstombs or wcstombs_s function

http://msdn.microsoft.com/en-us/library/5d7tc9zw%28v=vs.80%29.aspx



来源:https://stackoverflow.com/questions/6006319/converting-tchar-to-string-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!