输出包含所有转义字符的C ++字符串 [英] Output a C++ string including all escape characters
问题描述
我有一个像这样的字符串:
I have a string like this:
string s = "\t Hello \n";
打印时,它会给我一个选项卡,然后是Hello,然后是新行。但是,无论如何我都可以打印出来,以便在控制台中看到它:
When I print it then it gives me a tab then Hello then a new line. However, is there anyway I can print it such that I see this in my console:
\t Hello \n
换句话说,我希望字符串忽略转义字符并将其视为实际字符串? / p>
In other words, I want the string to disregard the escape characters and treat it as an actual string?
推荐答案
换句话说,我希望字符串忽略转义字符并将其视为实际字符
In other words, I want the string to disregard the escape characters and treat it as an actual string?
如所示,如果字符串是硬编码的,则可以对其进行修改以使用:
If the string is hard coded, as you show, you can modify it to use:
string s = "\\t Hello \\n";
如果您希望能够处理程序中抛出的任何字符串,则必须编写
If you want to be able to handle any string thrown at your program, you'll have to write a function and deal with all the escape sequences allowed by the language.
std::ostream& writeString(std::ostream& out, std::string const& s)
{
for ( auto ch : s )
{
switch (ch)
{
case '\'':
out << "\\'";
break;
case '\"':
out << "\\\"";
break;
case '\?':
out << "\\?";
break;
case '\\':
out << "\\\\";
break;
case '\a':
out << "\\a";
break;
case '\b':
out << "\\b";
break;
case '\f':
out << "\\f";
break;
case '\n':
out << "\\n";
break;
case '\r':
out << "\\r";
break;
case '\t':
out << "\\t";
break;
case '\v':
out << "\\v";
break;
default:
out << ch;
}
}
return out;
}
用作:
writeString(std::cout, s);
这篇关于输出包含所有转义字符的C ++字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!