【问题标题】:cout a string gets the address instead of value [duplicate]cout一个字符串获取地址而不是值[重复]
【发布时间】:2014-07-23 08:04:54
【问题描述】:

有一个宏定义如下:

#ifdef UNICODE
typedef wchar_t     TCHAR;
#define TEXT(quote) L##quote
#else
typedef char        TCHAR;
#define TEXT(quote) quote
#endif

当我尝试使用 std::cout 打印消息时,如下所示:

TCHAR* test = TEXT("test");
cout << test;

我得到的地址是 00D82110 而不是值“test”。

任何人都可以提出任何建议,我如何在此处打印值?非常感谢!

【问题讨论】:

    标签: c++ macros cout


    【解决方案1】:

    对于宽字符,您需要使用 wcout 而不是 cout。这样做:

    #ifdef UNICODE
        typedef wchar_t     TCHAR;
        #define TEXT(quote) L##quote
        #define COUT        wcout
    #else
        typedef char        TCHAR;
        #define TEXT(quote) quote
        #define COUT        cout
    #endif
    

    然后:

    TCHAR* test = TEXT("test");
    COUT << test;
    

    【讨论】:

    • 不是“可能”,而是“肯定”。 cout 不支持 wchar_t 数据,wcout 不支持 char 数据。将wchar_t* 传递给coutchar* 传递给wcout 最终都会调用void* 流操作符,这就是打印内存地址而不是文本的原因。
    • @RemyLebeau:我知道。我为其他方法(UTF8 格式的字符串等!)的建议留出了空间:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-17
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 2021-08-08
    相关资源
    最近更新 更多