c++ - 在 visual studio 和 eclipse 中打印 wchar_t 会给出不同的结果

标签 c++ visual-studio pointers cross-platform

我在 Windows x64 上使用 eclipse 和 Visual Studio。当我通过将指针递增 1 在 vi​​sual studio 中打印以下字符串时,它在 visual studio 中显示正确的结果。但是在 eclipse 中,指针前进了 4 而不是前进了 1。为什么会有这种差异? eclipse中如何让指针也前进1?

输入字符串

[{"scaleFactor":4,"ball":{"radius":0.03999999910593033}}]

代码

unsigned char* temp = fileUtils->getFileData("levels.json", "r", &size);
wchar_t *levelData  = new wchar_t[size];
size_t len_or_error = 0;
if(size > 0) {
    const char* temp1 = reinterpret_cast<const char*>(temp);
    len_or_error = mbstowcs(&levelData[0], &temp1[0], size);
}
for(int i = 0; i < 100; i++) {
    CCLOG("i = %d | %s ", i, levelData + i);
}

输出与 12

i = 0 | [
i = 1 | { 
i = 2 | " 
i = 3 | s 
i = 4 | c 
i = 5 | a 
i = 6 | l 

输出 ECLIPSE

i = 0 | [{"scaleFactor":4,"ball":{"radius":0.03999999910593033}}]
i = 1 | caleFactor":4,"ball":{"radius":0.03999999910593033}}]
i = 2 | Factor":4,"ball":{"radius":0.03999999910593033}}]
i = 3 | or":4,"ball":{"radius":0.03999999910593033}}]
i = 4 | 4,"ball":{"radius":0.03999999910593033}}]

更新 忘了说我在 Android 设备上运行 eclipse 版本,而不是在 Windows 本身上运行。

更新 2

在打印 wchar_t 之前添加了额外的代码。

CCLOG 是 cocos2d-x 的默认记录器 https://github.com/cocos2d/cocos2d-x

最佳答案

您遇到的问题是,与其他编译器(例如 GCC)相比,VC++ 编译器的 wchar_t 大小不同。

Windows 使用 two bytes to represent wchar_t .您的代码在 Visual Studio 中似乎可以正常工作,因为您告诉格式字符串说明符读取一个窄字符串(一个字节)。您应该使用 %ls 而不是 %s 来正确读取宽字符串。但是,我认为您真正想要做的是阅读一个字符。为此,请尝试:

printf("i = %d | %lc\r\n ", i, *( levelData + i ) );

您没有指定您在 Eclipse 中使用的编译器,但是 GCC(我认为是 MinGW)最多使用 4 个字节来存储 wchar_t,这就是它跳转 4 个字节的原因.参见 How big is wchar_t with GCC?看起来它也在使用可变长度编码来存储数据。

关于c++ - 在 visual studio 和 eclipse 中打印 wchar_t 会给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16644130/

相关文章:

VS Code 中的 HTML 标记验证器 - 警告重复属性

c++ - 在这里使用指针 vector 是不必要的还是更糟,导致内存泄漏?

c - C 中的二维数组指针

c++ - 来自 const std::vector<>& 的自动;对象还是引用?

c++ - 如何使用客户端套接字绑定(bind)

c++ - 从第 3 方库导出 cpp 损坏的函数

c - C 中 fwrite 和 struct 的奇怪错误

c++ - protected 继承错误

c++ - 很难在 multimap<Class object, enum> 上使用 max_element(也有 min_element)

css - 在 VS 中发布网站时 @import "theme.css"不起作用