Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 637
Christopher LaChance Avatar asked Jun 01 '17 18:06

Christopher LaChance


2 Answers

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
like image 153
R Sahu Avatar answered Sep 29 '22 11:09

R Sahu


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!"
}
like image 23
templatetypedef Avatar answered Sep 29 '22 13:09

templatetypedef