繁体   English   中英

std :: string本地编码为UTF-8但char不能保存utf字符?

[英]std::string is natively encoded in UTF-8 but char can not hold utf characters?

在阅读std :: wstring VS std :: string后 ,我的印象是,对于Linux ,我不需要担心使用该语言的任何宽字符设施。
*类似于: std :: wifstreamstd :: wofstreamstd :: wstringwhar_t等。

当我只使用std :: strings作为非ascii字符时,这似乎很好,但是当我使用字符来处理它们时却没有。

例如:我有一个只带有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;

}

同样的程序工作,但是,如果我在的地方的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,您应该读入一个char数组。 或者只是std :: string,因为那已经有效了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM