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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With