C++ wchart_t 警告 : character constant too long for its type

标签 c++ types wchar-t

//更新1:

代码块 16.01
海湾合作委员会 4.9.2
Windows 10

我正在努力理解:

  1. wchar_t有什么用?
  2. char16_t 和 wchar_t 有什么区别?
    我知道 char16_t 的大小保证为 16 位,但在这种特殊情况下,它们的大小相同。
  3. 每种字符类型的正确文字是什么?

计划目标:

  • 打印 U+0000 到 U+FFFF 范围内的所有 Unicode 字符。

//结束更新1

当我编译以下代码时:

#include <iostream>

int main(void)

{
    std::cout << sizeof(wchar_t) << "\n";
    for (wchar_t ch = u'\u0000'; ch <= u'\uffff'; ++ch)
        std::wcout << " " << ch;

    std::cout << "\n\n\n";
}

我在 for 语句的行中收到以下警告:“字符常量对于其类型而言太长”。

我运行了程序,得到了这个:output .

我在网上搜索了一下,所有我能找到的是 wchar_t 大小是实现定义的,但即使如此,它在我的系统上也是 2 个字节。我认为它足够大。

Q1:为什么我会收到警告?
Q2:为什么输出的字符数少?我预计会有数千个。

最佳答案

以下内容可能更符合预期,将从 U+0000 到 U+FFFF 的每个可打印代码点显示为 Unicode。请务必将控制台字体设置为 Unicode 字体。

#include <cstdlib>
#include <cwctype>
#include <locale>
#include <iostream>

#if _WIN32 || _WIN64
// Windows needs a little non-standard magic for this to work.
#include <io.h>
#include <fcntl.h>
#include <locale.h>
#endif

using std::wint_t;
using std::iswprint;

void init_locale(void)
// Does magic so that wcout can work.
{
#if _WIN32 || _WIN64
  // Windows needs a little non-standard magic.
  constexpr char cp_utf16le[] = ".1200";
  setlocale( LC_ALL, cp_utf16le );
  _setmode( _fileno(stdout), _O_WTEXT );
#else
  // The correct locale name may vary by OS, e.g., "en_US.utf8".
  constexpr char locale_name[] = "";
  std::locale::global(std::locale(locale_name));
  std::wcout.imbue(std::locale());
#endif
}

int main(void)
{
    init_locale();

    for ( unsigned long i = 0; i < 0x10000UL; ++i )
      if (iswprint(static_cast<wint_t>(i)))
        std::wcout << static_cast<wchar_t>(i);

    std::wcout << std::endl;

    return EXIT_SUCCESS;
}

关于C++ wchart_t 警告 : character constant too long for its type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43025619/

相关文章:

c++ - 在 wcscpy_s 之后读取字符串的字符时出错

c++ - 如何检查模板类型参数是字符类型还是字符串类型?

c++ - 读取 Intel Hex 文件以对 C++ 进行排序

c++ - 为调试库运行项目时发布库出错

C++ flush() 不工作?不能使用 endl

go - 我们可以为 Go 中的错误创建子类型吗?

javascript - javascript变量可以包含任何东西吗?

c++ - 在 Windows 终端中输出 unicode 字符

c++ - select() block 而不是返回超时

PHP 和 Jquery 的 json