错误不完整的通用字符名称\ U.

rec*_*gle 6 c++ text-files

我正在尝试编写一个改变.txt文件的C++程序.但是,当我运行它时,我得到一个奇怪的错误.

错误:

6:20 C:\ Dev-Cpp\Homework6.cpp不完整的通用字符名称\ U.

我的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Bil*_*eal 21

"C:\Users\My Name\Desktop\test\input.txt"
反斜杠(\)是一个特殊字符.你必须逃脱它:
"C:\\Users\\My Name\\Desktop\\test\\input.txt".

编辑:或者,使用正斜杠(/).Windows并不关心.


Ada*_*eld 6

您需要在文件名中转义反斜杠.在C++字符串常量中,反斜杠是一个不代表自身的转义字符.要获得文字反斜杠,您需要使用双反斜杠\\.

\U是32位Unicode转义序列的前缀:您使用类似" \U0010FFFF"的东西来表示高Unicode字符.编译器抱怨这\Users...不是有效的Unicode转义序列,因为sers...它不是有效的十六进制数.

修复是使用字符串"C:\\Users\\My Name\\Desktop\\test\\input.txt".