Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ouputting String Literal from a variable

Tags:

c++

c++11

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
like image 557
Sean Avatar asked Jan 02 '23 05:01

Sean


2 Answers

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.

like image 184
Kostas Avatar answered Jan 05 '23 15:01

Kostas


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

like image 40
Michael Surette Avatar answered Jan 05 '23 15:01

Michael Surette