简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM