Search code examples
c++escapingnewlinestdout

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:

Hello
World

But I would like to print the string to stdout with the newline character escaped, so the output looks like:

Hello\nWorld

How can I do this without modifying the string literal?


Solution

  • The solution I opted for (thanks @RemyLebeau) is to create a copy of the string and escape the desired escape sequences ("\n" becomes "\\n").

    Here is the function which does this escaping:

    void escape_escape_sequences(std::string &str) {
      std::pair<char, char> const sequences[] {
        { '\a', 'a' },
        { '\b', 'b' },
        { '\f', 'f' },
        { '\n', 'n' },
        { '\r', 'r' },
        { '\t', 't' },
        { '\v', 'v' },
      };
    
      for (size_t i = 0; i < str.length(); ++i) {
        char *const c = str.data() + i;
    
        for (auto const seq : sequences) {
          if (*c == seq.first) {
            *c = seq.second;
            str.insert(i, "\\");
            ++i; // to account for inserted "\\"
            break;
          }
        }
      }
    }