为什么fstream不写入文件?

Why does fstream not write to the file?

我的代码:

ifstream studentList;
studentList.open("ListOfStudents.txt");
studentList << firstName << endl;
studentList.close();

每当我 运行 我的程序时,它都会说“'operator<<' 不匹配”。我一直在尝试解决这个问题,但没有任何效果。

提前致谢。

std::ifstream 仅用于输入(设置了 std::ios::in 标志),因此您不能写入它。

您需要改用 std::ofstream(仅输出),或 std::fstream 并显式设置 std::ios::out 标志。

ofstream studentList;
studentList.open("ListOfStudents.txt");
studentList << firstName << endl;
studentList.close();
fstream studentList;
studentList.open("ListOfStudents.txt", ios::out);
studentList << firstName << endl;
studentList.close();