[英]How to cout the std::basic_string<TCHAR>
I am trying to cout a basic_string<TCHAR>
. 我想尝试一个
basic_string<TCHAR>
。 But cout is throwing error. 但是cout正在抛出错误。 Can I know how to do that
我可以知道该怎么做
As dauphic said, std::wcout
is for wide strings and std::cout
for narrow ones. 正如dauphic所说,
std::wcout
用于宽字符串, std::cout
用于窄字符串。 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: 如果你想能够为任何一种类型的字符串进行编译(
TCHAR
意味着使这类事情变得更容易),这样的事情有时会让生活更轻松:
#if defined(UNICODE) || defined(_UNICODE)
#define tcout std::wcout
#else
#define tcout std::cout
#endif
With this in place use tcout instead. 有了这个使用tcout而不是。
TCHAR
is a winapi define for the character type used by your application. TCHAR
是应用程序使用的字符类型的winapi定义。 If you have the character set as multi-byte characters, it will be char
. 如果将字符集设置为多字节字符,则它将为
char
。 If you have it set to Unicode, it will be wchar_t
. 如果将它设置为Unicode,
wchar_t
。
If it's wchar_t
, you need to use std::wcout
. 如果是
wchar_t
,则需要使用std::wcout
。 Otherwise, just plain std::cout
should be fine. 否则,只是普通的
std::cout
应该没问题。
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. 通常,它也有助于解释你得到的错误,但很可能你试图将
std::basic_string<wchar_t>
插入到std::cout
,并且可能没有operator<<
overload。
As @Bo Persson mentioned, another way of defining a tcout
type would be using references with the correct stream types . 正如@Bo Persson所提到的,定义
tcout
类型的另一种方法是使用具有正确流类型的 引用 。 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).
这也适用于预编译头(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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.