4

I want to know if it is possible to output a raw string from a preset variable whose value I cannot change. For example:

string test = "test\ntest2";
cout << test;

would output

test
test2

Is it possible to run similar code as above but change the cout statement to print the raw string like so:

test\ntest2
idmean
  • 14,540
  • 9
  • 54
  • 83
Sean
  • 155
  • 2
  • 7
  • 2
    How about basic escaping `"test\\ntest2"`? – idmean Jun 20 '18 at 17:15
  • The variable is set, I cannot change it, as stated in my question. – Sean Jun 20 '18 at 17:25
  • I see. The last paragraph was misleading because it implied that you could change the literal. (But I edited mainly so that I could retract my vote...) – idmean Jun 20 '18 at 17:27
  • Are you trying to get _the original_ representation, or just _an unambiguous_ representation? – Davis Herring Jun 20 '18 at 17:41
  • The brute force way would be to replace every occurrence of `"\n"` with `"\\n"` in your string (and then repeat for all the other escape sequences). See the SO question [How to replace all occurrences of a character in string?](https://stackoverflow.com/q/2896600/654614) for code. – Frank Boyne Jun 20 '18 at 17:48
  • `qDebug()` from the Qt library does something like that. Perhaps take a look at how that it implemented (it's open source). – Jesper Juhl Jun 20 '18 at 18:16

2 Answers2

7

An escape sequence \x is translated into only one character.

There are probably some platforms out there for which an endline character is printed as \n but this is solely implementation dependent.

Translating this then to two characters (\ and x), would mean you would have to modify the string itself.

The easiest way of doing that is making a custom function.

void print_all(std::string s)
{
    for (char c : s) {
        switch (c) {
            case '\n' : std::cout << "\\n"; break;
            case '\t' : std::cout << "\\t"; break;

            // etc.. etc..

            default : std::cout << c;
        }
    }
}

For all escape sequences you care about.

Note: unlike ctrl-x and x, there is no direct correlation between the values of \x and x, at least in the ASCII table, so a switch statement is necessary.

Kostas
  • 4,061
  • 1
  • 14
  • 32
2

You could also use raw string literals if you have c++11.

#include <iostream>

using namespace std;

int main()
{
    cout << R"(test\ntest2)" << endl;
    return 0;
}

Mike

Michael Surette
  • 701
  • 1
  • 4
  • 12
  • I had it originally in my post, but it seems it was edited out, but I cannot access the string stored in the variable at all, I have to use the variable declaration – Sean Jun 21 '18 at 21:00