c++ - std::string 本身是用 UTF-8 编码的,但 char 不能保存 utf 字符?

标签 c++ string unicode utf widechar

看完std::wstring VS std::string ,我的印象是对于 Linux,我不需要担心使用该语言的任何宽字符功能。
*诸如:std::wifstreamstd::wofstreamstd::wstringwhar_t 等.

当我只对非 ascii 字符使用 std::strings 时,这似乎没问题,但当我使用 chars 来处理它们时,情况就不是这样了。

例如:我有一个文件,其中只有一个 unicode 复选标记。
我可以读入它,将它打印到终端,然后将它输出到一个文件。

// ✓ reads in unicode to string
// ✓ outputs unicode to terminal
// ✓ outputs unicode back to the file
#include <iostream>
#include <string>
#include <fstream>

int main(){
  std::ifstream in("in.txt");
  std::ofstream out("out.txt");

  std::string checkmark;
  std::getline(in,checkmark); //size of string is actually 3 even though it just has 1 unicode character

  std::cout << checkmark << std::endl;
  out << checkmark;

}

但是,如果我使用 char 代替 std::string,则相同的程序工作:

// ✕ only partially reads in unicode to char
// ✕ does not output unicode to terminal
// ✕ does not output unicode back to the file
#include <iostream>
#include <string>
#include <fstream>

int main(){
  std::ifstream in("in.txt");
  std::ofstream out("out.txt");

  char checkmark;
  checkmark = in.get();

  std::cout << checkmark << std::endl;
  out << checkmark;

}

终端中没有任何内容出现(除了换行符)。
输出文件包含 â 而不是复选标记字符。

由于 char 只有一个字节,我可以尝试使用 whar_t,但它仍然不起作用:

// ✕ only partially reads in unicode to char
// ✕ does not output unicode to terminal
// ✕ does not output unicode back to the file
#include <iostream>
#include <string>
#include <fstream>

    int main(){
      std::wifstream in("in.txt");
      std::wofstream out("out.txt");

      wchar_t checkmark;
      checkmark = in.get();

      std::wcout << checkmark << std::endl;
      out << checkmark;

    }

我还阅读了有关设置以下语言环境的内容,但似乎没有什么不同。

setlocale(LC_ALL, "");

最佳答案

在 std::string 的情况下,您读取一行,在我们的例子中,它包含一个多字节 Unicode 字符。在 char 的情况下,您读取的是一个字节,它甚至不是一个完整的字符。

编辑:对于 UTF-8,您应该读入一个字符数组。或者只是 std::string 因为它已经有效。

关于c++ - std::string 本身是用 UTF-8 编码的,但 char 不能保存 utf 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25395509/

相关文章:

c++ - 将结构推回结构中的 vector

python - 用星号替换字符串中的所有字符

c - 读取特定格式的字符串

python - ipython笔记本中的Unicode输出

c++ - 代码 C++ 中的动态多态性错误

c++ - 查找未使用的包含标题的工具?

c++ - 如何从C++中的对象数组中获取数据成员数组?

python - 正则表达式分割字符串而不考虑引号中的空格

javascript - 如何检查 Javascript 中 Unicode 字符串的相等性?

r - Shiny 应用程序中的 Unicode 文本