5

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?

Martin Geisler
  • 72,968
  • 25
  • 171
  • 229
AspiringMat
  • 2,161
  • 2
  • 21
  • 33
  • 2
    Possible duplicate of [using \ in a string as literal instead of an escape](http://stackoverflow.com/questions/12103445/using-in-a-string-as-literal-instead-of-an-escape) – Alexander Mar 10 '17 at 06:05

3 Answers3

4

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);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

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

string s = "\\t Hello \\n";
richard_d_sim
  • 793
  • 2
  • 10
  • 23
0

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

string s = "\\t Hello \\n";
msc
  • 33,420
  • 29
  • 119
  • 214