Converting _TCHAR* to char*

久未见 提交于 2019-12-01 05:45:29

The quickest solution is to just change the signature to the standard one. Replace:

int _tmain( int argc, _TCHAR* argv[] )

With

int main( int argc, char *argv[] )

This does mean on Windows that the command line arguments get converted to the system's locale encoding and since Windows doesn't support UTF-8 here not everything converts correctly. However unless you actually need internationalization then it may not be worth your time to do anything more.

_TCHAR, i.e. TCHAR is a type that depends on your project's settings. It can be either wchar_t (when you use Unicode) or char (when you use Multi-byte). You will find this in Project Properties - General, there's a setting Character Set.

Probably the simplest thing that you could do is just to use multi-byte option and treat _TCHAR* type as a simple char* and use it to construct std::string object ASAP:

std::string filename(argv[1]);

But in case you are going to work with special characters A LOT, then I find it more reasonable to use Unicode and hold strings in form of std::wstring objects wherever it's possible. If that's the case, then just use std::wstring's constructor instead:

std::wstring filename(argv[1]);

And in case you'll end up working with wide strings, sometimes you'll need a conversion between wide strings and multi-byte strings and these helpers might help you:

// multi byte to wide char:
std::wstring s2ws(const std::string& str)
{
    int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
    std::wstring wstrTo(size_needed, 0);
    MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
    return wstrTo;
}

// wide char to multi byte:
std::string ws2s(const std::wstring& wstr)
{
    int size_needed = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), int(wstr.length() + 1), 0, 0, 0, 0); 
    std::string strTo(size_needed, 0);
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), int(wstr.length() + 1), &strTo[0], size_needed, 0, 0); 
    return strTo;
}
yevgeniy litvinov

other than reading the 26,000 page cpp 2003 VS manual which hasn't changed much.... std::string test(print); test = "";

int _tmain( int argc, _TCHAR* argv[] )  

int main( int argc, char *argv[] ) 

work the same unless you were using some securitys function.... and couldn't be unicode in the character set property ... if you were to use the CreateFile function in file Management Functions unless you multi-threaded it somehow

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