Christopher LaChance
Christopher LaChance

Reputation: 261

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

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"

Upvotes: 12

Views: 11301

Answers (3)

templatetypedef
templatetypedef

Reputation: 372992

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!"
}

Upvotes: 2

Geordie
Geordie

Reputation: 2184

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
)";

Upvotes: -2

R Sahu
R Sahu

Reputation: 206697

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?

No.

However, you can write a function that substitutes the characters that are defined by escape sequences by an appropriate string, i.e. replace the character '\t' by the string "\\t".

Sample program:

#include <iostream>
#include <string>

// Performs only one substitution of \t.
// Needs to be updated to do it for all occurrences of \t and
// all other escape sequences that can be found in raw strings.    
std::string toRawString(std::string const& in)
{
   std::string ret = in;
   auto p = ret.find('\t');
   if ( p != ret.npos )
   {
      ret.replace(p, 1, "\\t");
   }

   return ret;
}

int main()
{
   std::string TestString = "Test\tString";
   std::cout << toRawString(TestString) << std::endl;
}

Output:

Test\tString

Upvotes: 6

Related Questions