[英]Escaping newline character when writing to stdout in C++
I have a string in my program containing a newline character:我的程序中有一个包含换行符的字符串:
char const *str = "Hello\nWorld";
Normally when printing such a string to stdout the \n creates a new line, so the output is:通常在将这样的字符串打印到标准输出时,\n 会创建一个新行,因此 output 是:
Hello
World
But I would like to print the string to stdout with the newline character escaped, so the output looks like:但我想将字符串打印到标准输出并转义换行符,所以 output 看起来像:
Hello\nWorld
How can I do this without modifying the string literal?如何在不修改字符串文字的情况下做到这一点?
The solution I opted for (thanks @RemyLebeau ) is to create a copy of the string and escape the desired escape sequences ( "\n"
becomes "\\n"
).我选择的解决方案(感谢@RemyLebeau )是创建字符串的副本并转义所需的转义序列(
"\n"
变为"\\n"
)。
Here is the function which does this escaping:这是执行此 escaping 的 function:
void escape_escape_sequences(std::string &str) {
for (size_t i = 0; i < str.length();) {
char const c = str[i];
char rawEquiv = '\0';
if (c == '\n') rawEquiv = 'n';
else if (c == '\t') rawEquiv = 't';
else if (c == '\r') rawEquiv = 'r';
else if (c == '\f') rawEquiv = 'f';
if (rawEquiv != '\0') {
str[i] = rawEquiv;
str.insert(i, "\\");
i += 2;
} else {
++i;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.