I think you need an escaping function that takes arbitrary text and escapes it so that it uses the syntax of a C++ string literal (minus the quotes). Maybe look around the web to see if there's a library already doing this.
There are some conventions to apply because there are multiple ways to escape a character.
I don't love this code, but here's an implementation I quickly put together to illustrate:
#include <string>
#include <iostream>
#include <sstream>
#include <iomanip>
const char* staticMap(char c) {
switch (c) {
case '\a': return "\\a";
case '\b': return "\\b";
case '\t': return "\\t";
case '\n': return "\\n";
case '\v': return "\\v";
case '\f': return "\\f";
case '\r': return "\\r";
case '\"': return "\\\"";
case '\'': return "\\\'";
case '\?': return "\\\?";
case '\\': return "\\\\";
}
return nullptr;
}
std::string escape_cpp(const std::string& input) {
std::stringstream ss;
for (char c : input) {
const char* str = staticMap(c);
if (str) {
ss << str;
} else if (!isprint(static_cast<unsigned char>(c))) {
ss << "\\u" << std::hex << std::setfill('0') << std::setw(4) << (static_cast<unsigned int>(static_cast<unsigned char>(c)));
} else {
ss << c;
}
}
return ss.str();
}
int main() {
std::string foo("bu\u00ffffalo\n\"\tw\u0000rld\"", 17);
// Will be printed as written (by convention).
std::cout << escape_cpp(foo) << std::endl;
}
\, not/. (Big difference.)'\n', print it as the two characters'\'and'n'. If it's any other special character, print it using some other special character sequence. Otherwise (if it's a regular character), print it as itself.'\'and'n', or the single character'\n'? (Again, big difference.)