可以将原始字符串修饰符R“()”与字符串变量结合使用吗?

Chr*_*nce 5 string string-literals c++11

例如:

string MyString = "Normal\tString";
cout << MyString << endl;
Run Code Online (Sandbox Code Playgroud)

产生以下内容: "Normal String"


原始字符串修饰符附加到字符串,如下所示:

string MyString = R"(Normal\tString)";
cout << MyString << endl;
Run Code Online (Sandbox Code Playgroud)

产生以下内容: "Normal\tString"


问题

有没有一种方法可以将原始字符串修饰符附加到包含字符串的变量中,以显示该变量中包含的字符串的原始形式?

string TestString = "Test\tString";
cout << R(TestString) << endl;
Run Code Online (Sandbox Code Playgroud)

这样就得到: "Test\tString"

R S*_*ahu 5

有没有办法将原始字符串修饰符附加到包含字符串的变量,以便打印变量中包含的字符串的原始形式?

不。

但是,您可以编写一个函数,将转义序列定义的字符替换为适当的字符串,即将字符替换'\t'为字符串"\\t"

示例程序:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

#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;
}
Run Code Online (Sandbox Code Playgroud)