如何编写包含双引号的字符串文字

发布于 2024-08-27 17:27:46 字数 204 浏览 11 评论 0原文

我需要在 C++ 中执行以下 C# 代码(如果可能)。我必须初始化一个长字符串,其中包含大量引号和其他内容。

// C# verbatim string
const String _literal = @"I can use "quotes" inside here";

I need to do the following C# code in C++ (if possible). I have to initialize a long string with lots of quotes and other stuff in it.

// C# verbatim string
const String _literal = @"I can use "quotes" inside here";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

新人笑 2024-09-03 17:27:46

这在 C++03(当前标准)中不可用。

这是 C++0x 草案标准的一部分,但目前尚未可用。

现在,您只需明确引用它:

const std::string _literal = "I have to escape my quotes in \"C++03\"";

一旦 C++0x 成为现实,您将能够

const std::string _literal = R"(but "C++0x" has raw string literals)";

在文字中编写:并且当您需要 )" 时:

const std::string _literal = R"DELIM(more "(raw string)" fun)DELIM";

That is not available in C++03 (the current standard).

That is part of the C++0x draft standard but that's not readily available just yet.

For now, you just have to quote it explicitly:

const std::string _literal = "I have to escape my quotes in \"C++03\"";

Once C++0x becomes reality, you'll be able to write:

const std::string _literal = R"(but "C++0x" has raw string literals)";

and when you need )" in your literal:

const std::string _literal = R"DELIM(more "(raw string)" fun)DELIM";
红颜悴 2024-09-03 17:27:46

C++ 中没有相当于 C# 的“@”。实现它的唯一方法是正确转义字符串:

const char *_literal = "I can use \"quotes\" inside here";

There is no equivalent of C#'s "@" in C++. The only way to achieve it is to escape the string properly:

const char *_literal = "I can use \"quotes\" inside here";
机场等船 2024-09-03 17:27:46

C++ 中没有原始字符串文字。您需要转义字符串文字。

std::string str = "I can use \"quotes\" inside here";

C++0x 在可用时提供原始字符串文字:

R"C:\mypath"

顺便说一下,您不应使用前导下划线命名任何内容,因为此类标识符在 C++ 中保留。

There is no raw string literals in C++. You'll need to escape your string literals.

std::string str = "I can use \"quotes\" inside here";

C++0x offers a raw string literal when it's available:

R"C:\mypath"

By the way you should not name anything with a leading underscore as such identifiers are reserved in C++.

白日梦 2024-09-03 17:27:46

C++中没有这样的机制。您必须以老式的方式进行操作,即使用转义符。

不过,您也许可以使用脚本语言来使转义部分更容易一些。例如,Ruby 中的 %Q 运算符在 irb 中使用时将返回正确转义的双引号字符串:

irb(main):003:0> %Q{hello "world" and stuff     with    tabs}
=> "hello \"world\" and stuff\twith\ttabs"

There is no such mechanism in C++. You'll have to do it the old fashioned way, by using escapes.

You might be able to use a scripting language to make the escaping part a little easier, though. For instance, the %Q operator in Ruby will return a properly escaped double-quoted string when used in irb:

irb(main):003:0> %Q{hello "world" and stuff     with    tabs}
=> "hello \"world\" and stuff\twith\ttabs"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文