AspiringMat
AspiringMat

Reputation: 2269

Output a C++ string including all escape characters

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?

Upvotes: 5

Views: 7308

Answers (3)

R Sahu
R Sahu

Reputation: 206607

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

Upvotes: 5

msc
msc

Reputation: 34608

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

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

Upvotes: 0

richard_d_sim
richard_d_sim

Reputation: 913

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

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

Upvotes: 0

Related Questions