How to cout the std::basic_string<TCHAR>

孤者浪人 提交于 2019-12-29 05:55:22

问题


I am trying to cout a basic_string<TCHAR>. But cout is throwing error. Can I know how to do that


回答1:


As dauphic said, std::wcout is for wide strings and std::cout for narrow ones. If you want to be able to compile for either type of string (TCHAR is meant to make this sort of thing easier) something like this sometimes makes life easier:

#if defined(UNICODE) || defined(_UNICODE)
#define tcout std::wcout
#else
#define tcout std::cout
#endif

With this in place use tcout instead.




回答2:


TCHAR is a winapi define for the character type used by your application. If you have the character set as multi-byte characters, it will be char. If you have it set to Unicode, it will be wchar_t.

If it's wchar_t, you need to use std::wcout. Otherwise, just plain std::cout should be fine.

Generally it helps to also explain what errors you're getting, but most likely you're trying to insert an std::basic_string<wchar_t> into std::cout, and there probably isn't an operator<< overload for that.




回答3:


As @Bo Persson mentioned, another way of defining a tcout type would be using references with the correct stream types. Though there are a few more things to consider when doing that, as you'll easily end up with linker issues due to multiple or missing definitions.

What works for me is declaring these types as external references in a header and defining them once in a source file. This also works in a precompiled header (stdafx).

Header

namespace std
{
#ifdef UNICODE
    extern wostream& tcout;
#else
    extern ostream& tcout;
#endif // UNICODE
}

Implementation

namespace std
{
#ifdef UNICODE
    wostream& tcout = wcout;
#else
    ostream& tcout = cout;
#endif // UNICODE
}


来源:https://stackoverflow.com/questions/5165160/how-to-cout-the-stdbasic-stringtchar

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