How to read from file UTF simbols as if they were UTF code?
So I have a file - html file there are lots of simbols like &'""""</开发者_如何学C\>9()!@#+=-
I need to convert them into a form that can be copied from output screen so to be after passed to std::string str ("Here should be UTF simbols");
how to do such thing (using C++ boost)
This code assumes the compiling system uses a superset of ASCII, which is reasonable on today's systems. It gives a string literal as a std::string, including surrounding quotes. The input data is treated as generic bytes rather than required to be 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();
}
Example:
// 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;
}
Output:
#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";
}
精彩评论