The problem is that the first line either needs to be a raw string literal or have \\
in it:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string q = R"(C:\Users\georg\Desktop\XY.txt)"; // Raw (C++11 and higher)
string q2 = "C:\\Users\\georg\\Desktop\\XY.txt"; // Escaped
cout << q << "\n" // Outputs: C:\Users\georg\Desktop\XY.txt
<< q2 << "\n"; // Outpits: C:\Users\georg\Desktop\XY.txt
}
As written, it is trying to use \U
, \g
, etc. as special characters.
Update: To actually do what you are asking, you'd want to do something like:
#include <string>
#include <iostream>
using namespace std;
// From http://stackoverflow.com/a/15372760/201787
void replaceAll( string &s, const string &search, const string &replace ) {
for( size_t pos = 0; ; pos += replace.length() ) {
// Locate the substring to replace
pos = s.find( search, pos );
if( pos == string::npos ) break;
// Replace by erasing and inserting
s.erase( pos, search.length() );
s.insert( pos, replace );
}
}
int main()
{
string q = R"(C:\Users\georg\Desktop\XY.txt)"; // Raw (C++11 and higher)
string q2 = "C:\\Users\\georg\\Desktop\\XY.txt"; // Escaped
string q3;
std::cin >> q3; // Does not handle whitespace
replaceAll( q, "\\", "\\\\" );
replaceAll( q2, "\\", "\\\\" );
replaceAll( q3, "\\", "\\\\" );
cout << q << "\n"
<< q2 << "\n"
<< q3 << "\n";
}
Which prints the following if the user enters C:\Users\georg\Desktop\XY.txt
:
C:\\Users\\georg\\Desktop\\XY.txt
C:\\Users\\georg\\Desktop\\XY.txt
C:\\Users\\georg\\Desktop\\XY.txt