c++ - 如何从文件中读取 UTF 符号,就好像它们是 UTF 代码一样?

标签 c++ string boost utf

所以我有一个文件 - html 文件有很多像 &'""""</\>9()!@#+=- 这样的符号我需要将它们转换成可以从输出屏幕复制的形式,以便在传递给 std::string str ("Here should be UTF simbols"); 之后如何做这样的事情(使用 C++ boost)

最佳答案

此代码假定编译系统使用 ASCII 的超集,这在当今的系统上是合理的。它将字符串文字作为 std::string 给出,包括周围的引号。输入数据被视为通用字节,而不是必须为 UTF-8。

std::string string_literal(int length, char const *data) {
  std::stringstream s;
  std::ostream shex (s.rdbuf());
  shex << std::hex << std::uppercase;
  shex.fill('0');

  s << '"';
  for (int n = 0; n != length; ++n) {
    unsigned char c = data[n];
    if (c < 32 || 0x7F <= c) {
      // add special cases for \n, \t, \r, etc. to produce nicer output
      shex << "\\x" << std::setw(2) << int(c);
    }
    else {
      switch (c) {
      case '"':
      case '\\':
        s << '\\' << c;
        break;

      default:
        s << c;
      }
    }
  }
  s << '"';
  return s.str();
}

例子:

// for string literals, makes below example easier
template<int N>
std::string string_literal(char const (&data)[N]) {
  assert(data[N - 1] == '\0');
  return string_literal(N - 1, data);
}

// another convenience overload
std::string string_literal(std::string const &s) {
  return string_literal(s.length(), s.data());
}

int main() {
  std::cout << "#include <iostream>\nint main() {\n  std::cout << ";
  std::cout << string_literal("&'\"</\\>9()!@#+=-") << "\n            << ";
  std::cout << string_literal("☺ ☃ ٩(•̮̮̃•̃)۶") << ";\n}\n";
    // first and second are a smiley face and snowman
    // the third may not display correctly on your browser
  return 0;
}

输出:

#include <iostream>
int main() {
  std::cout << "&'\"</\\>9()!@#+=-"
            << "\xE2\x98\xBA \xE2\x98\x83 \xD9\xA9(\xE2\x80\xA2\xCC\xAE\xCC\xAE\xCC\x83\xE2\x80\xA2\xCC\x83)\xDB\xB6";
}

关于c++ - 如何从文件中读取 UTF 符号,就好像它们是 UTF 代码一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4324143/

相关文章:

c - 如何在C中使用二维数组

c++ - 如何在 boost 中获取当前的 UTC 日期?

c++ - 在 C++11 中实现现有的网络接口(interface),定义关于字节序的位域

c++ - 在 boost 上从 bitset 到 bitset 的无序(哈希)映射

c++ - 大std::vector的加速创建

C++ 没有合适的默认构造函数可用 - 继承的模板化构造函数没有参数

python - codingbat python 字符串计数

C内存重叠?

c++ - 使用 boost QT 和 mingw 的多线程

c++ - 查找未排序数组的模式,以及该数组是否具有多个模式或没有模式