Output a C++ string including all escape characters

馋奶兔 提交于 2020-01-04 05:25:15

问题


I have a string like this:

string s = "\t Hello \n";

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

In other words, I want the string to disregard the escape characters and treat it as an actual string?


回答1:


You would need to escape the backslash so it would look something like this

string s = "\\t Hello \\n";



回答2:


Put doublebackslash because \\ doublebackslash produce a \ single backslash.

string s = "\\t Hello \\n";



回答3:


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;
}

Use it as:

writeString(std::cout, s);


来源:https://stackoverflow.com/questions/42711201/output-a-c-string-including-all-escape-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!