所以我有一个文件 - 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/