Domanda

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.

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

 ofstream fout;
 fout << the_string << endl;

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

È stato utile?

Soluzione

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

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 raw string literal1

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

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

Altri suggerimenti

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.

I hope I understood your question correctly:

Escape \ and escape ":

\\\"

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).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top