How to print \ "in C ++

I need to print a line that exactly matches:

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

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

I want to write the above line through a stream, so something like

  ofstream fout; fout << the_string << endl; 

The problem is that I cannot execute \\" inside the line.

+4
source share
4 answers

Just avoid the slash as well as the quote! That is, \"\\\"

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

in C ++ 0x / C ++ 11

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

which uses a string literal 1

See both real-time tested versions http://ideone.com/TgtZK

1 Why is it not surprising that syntax highlighting for ideone.com and stackoverflow have not yet been prepared :)

+5
source

It works:

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

Print

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

The point is, you need to avoid slash and quote.

+1
source

I hope I understood your question correctly:

Escape \ and Escape " :

\\\"

0
source

You might want to add the extra character "/" because the single "/" will not be parsed as a string. I think it should work (I'm a Java / C # guy, and I ran into this problem a couple of times).

0
source

Source: https://habr.com/ru/post/1379901/


All Articles