如何在 C++ 中打印 \"

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8029783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:53:08  来源:igfitidea点击:

how to print \" in C++

c++printingofstreamquotations

提问by user788171

I need to print a string that says exactly:

我需要打印一个字符串,准确地说:

std::string("-I\"/path/to/dir\" ");

Basically, I need to do this because I am using C++ code to generate C++ code.

基本上,我需要这样做,因为我使用 C++ 代码来生成 C++ 代码。

I want to write the above string via an ofstream, so something like

我想通过一个 ofstream 写上面的字符串,所以像

 ofstream fout;
 fout << the_string << endl;

The problem is that I cannot do \\"inside a string.

问题是我不能\\"在字符串里面做。

回答by sehe

Just escape the slash as well asthe quotes! I.e. \"--> \\\"

只需避开斜杠引号!即\"-->\\\"

fout << "std::string(\"-I\\"/path/to/dir\\" \");" << std::endl;

in C++0x/C++11

在 C++0x/C++11

fout << R"(std::string("-I\"/path/to/dir\" ");)" << std::endl;

which uses a raw string literal1

它使用原始字符串文字1

See both versions tested live at http://ideone.com/TgtZK 

http://ideone.com/TgtZK 上查看现场测试的两个版本 

1For which unsurprisingly the syntax highlighters for ideone.com and stackoverflow are not yet prepared :)

1意料之中的是,ideone.com 和 stackoverflow 的语法高亮器还没有准备好:)

回答by Adam Zalcman

This works:

这有效:

#include <iostream>

using std::cout;
using std::endl;

int main() {
  cout << "std::string(\"-I\\"/path/to/dir\\" \");" << endl;
  return 0;
}

printing

印刷

std::string("-I\"/path/to/dir\" ");

The point is: you need to escape both the slash and the quote.

关键是:您需要同时转义斜杠和引号。

回答by Мitke

You might wanna try to put additional "/" character, because the single "/" will not be parsed as string. I think it should work (I'm Java/C# guy, and I have encountered this problem myself couple of times).

您可能想尝试添加额外的“/”字符,因为单个“/”不会被解析为字符串。我认为它应该可以工作(我是 Java/C# 人,我自己也遇到过这个问题几次)。

回答by Karoly Horvath

I hope I understood your question correctly:

我希望我正确理解了你的问题:

Escape \and escape ":

逃脱\和逃脱"

\\\"

\\\"