4

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.

sehe
  • 374,641
  • 47
  • 450
  • 633
user788171
  • 16,753
  • 40
  • 98
  • 125

5 Answers5

9

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

sehe
  • 374,641
  • 47
  • 450
  • 633
1

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.

Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
0

This works as an answer to the title question even it's not your issue :

#include <iostream>
using namespace std;

int main(){
    std::string foo = string(" /!\\ WARNING /!\\ -> 1");
    cout << foo << endl;
    cout << " /!\\ WARNING /!\\ -> 2" << endl;
    return 0;
}

Output of this is :

/!\ WARNING /!\ -> 1

/!\ WARNING /!\ -> 2

Nawem
  • 23
  • 5
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Paul Floyd Feb 10 '23 at 08:35
0

I hope I understood your question correctly:

Escape \ and escape ":

\\\"

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
0

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

Мitke
  • 310
  • 3
  • 17