Escaping newline character when writing to stdout in C++

Viewed 30

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?

1 Answers

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) {
  for (size_t i = 0; i < str.length();) {
    char const c = str[i];

    char rawEquiv = '\0';
    if (c == '\n') rawEquiv = 'n';
    else if (c == '\t') rawEquiv = 't';
    else if (c == '\r') rawEquiv = 'r';
    else if (c == '\f') rawEquiv = 'f';

    if (rawEquiv != '\0') {
      str[i] = rawEquiv;
      str.insert(i, "\\");
      i += 2;
    } else {
      ++i;
    }
  }
}
Related