I'm trying to write a C++ program that alters a .txt file. However when I run it I get a strange error.
The error:
6:20 C:\Dev-Cpp\Homework6.cpp incomplete universal character name \U
My code:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("C:\Users\My Name\Desktop\test\input.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
What am I doing wrong?
"C:\Users\My Name\Desktop\test\input.txt"
The backslash (\
) is a special character. You must escape it:"C:\\Users\\My Name\\Desktop\\test\\input.txt"
.
EDIT: Alternately, use forward slashes (/
). Windows doesn't care.
You need to escape your backslashes in the filename. In C++ string constants, backslash is an escape character which doesn't represent itself. To get a literal backslash, you need to use a double backslash \\
.
\U
is the prefix for a 32-bit Unicode escape sequence: you'd use something like "\U0010FFFF
" to represent a high Unicode character. The compiler is complaining that \Users...
is not a valid Unicode escape sequence, since sers...
is not a valid hexadecimal number.
The fix is to use the string "C:\\Users\\My Name\\Desktop\\test\\input.txt"
.
You need to use double backslashes there. So "C:\\Users...
. Otherwise you're starting an escape sequence (in this case \U for a unicode literal).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With