Can you combine the raw string modifier R"()" with a string variable?

Viewed 6993

Example

For example:

string MyString = "Normal\tString";
cout << MyString << endl;

produces the following: "Normal String"


Appending the raw string modifier to the string like so:

string MyString = R"(Normal\tString)";
cout << MyString << endl;

produces the following: "Normal\tString"


The Question

Is there a way to append the raw string modifier to a variable containing a string in order to print the raw form of the string contained within the variable?

string TestString = "Test\tString";
cout << R(TestString) << endl;

So you get: "Test\tString"

3 Answers

This question is tagged as C++11, in which case rolling your own conversion function is probably the best call.

However, if you have a C++14 compiler, you can use the std::quoted stream manipulator:

#include <iostream>
#include <iomanip>

int main() {
    string s = "Hello\tWorld!";
    std::cout << std::quoted(s) << std::endl; // Prints "Hello\tWorld!"
}

Kind of. This works but it's not a pretty solution:

std::string strToInsert = " insert this "
std::string myRawString = R"(
raw string raw string raw string
raw string raw string raw string
)"; myRawString += strToInsert; myRawString += R"(raw string
raw string raw string raw string
)";
Related