0

だから私はファイルを持っています-htmlファイルには&'""""</\>9()!@#+=-、出力画面からコピーできるフォームに変換する必要があるような多くのシンボルがあるので、そのstd::string str ("Here should be UTF simbols");ようなことを行う方法に渡された後です(C++ブーストを使用)

4

1 に答える 1

1

このコードは、コンパイル システムが 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";
}
于 2010-12-01T12:52:28.737 に答える