我需要将以下C#代码转换成C++(如果可能的话)。我需要用很多引号和其他内容初始化一个长字符串。
// C# verbatim string
const String _literal = @"I can use "quotes" inside here";
// C# verbatim string
const String _literal = @"I can use "quotes" inside here";
这在C++03(当前的标准)中不可用。
这是C++0x草案标准的一部分,但目前还不容易获得。
现在,你只需要显式地引用它:
const std::string _literal = "I have to escape my quotes in \"C++03\"";
一旦C++0x成为现实,你将能够编写:
Once C++0x becomes reality, you'll be able to write:const std::string _literal = R"(but "C++0x" has raw string literals)";
当您需要在文字字面值中包含 )"
时:
const std::string _literal = R"DELIM(more "(raw string)" fun)DELIM";
)"
)。 - R Samuel KlatchkoC++ 中没有类似于 C# 的 "@" 符号。唯一的方式就是正确转义字符串:
const char *_literal = "I can use \"quotes\" inside here";
C++中没有原始字符串字面量。您需要转义字符串字面量。
std::string str = "I can use \"quotes\" inside here";
C++0x提供了原始字符串字面量,当它可用时:
R"C:\mypath"
顺便提一下,在C++中应避免使用以下划线开头的命名,因为这些标识符是保留的。
R"(C:\mypath)"
。 - R Samuel KlatchkoC++中没有这样的机制。您需要使用转义字符来完成。
您可能可以使用脚本语言来使转义部分变得更加容易。例如,在Ruby中,使用%Q
操作符将在irb
中返回一个正确转义的双引号字符串:
irb(main):003:0> %Q{hello "world" and stuff with tabs}
=> "hello \"world\" and stuff\twith\ttabs"