所以我有这个写入文本文件的函数,但我一直收到这个错误,我相信这与使用 ofstream 的输出语法有关。 有人可以帮我诊断一下吗?
谢谢,
艾文
int writeSave(string chName, string chSex, string chRace,
vector<int> chAttributes, int chLevel, int chStage)
{
ofstream outputFile("saveFile.txt");
outputFile << "chName: " << chName <<
"\nchSex: " << chSex <<
"\nchRace: " << chRace <<
"\nchAttributes: " << chAttributes <<
"\nchLevel: " << chLevel <<
"\nchStage: " << chStage;
return 0;
}
运行/home/ubuntu/workspace/saveGame/sgFunc.cpp
/home/ubuntu/workspace/saveGame/sgFunc.cpp: In function ‘int writeSave(std::string, std::string, std::string, std::vector<int>, int, int)’: /home/ubuntu/workspace/saveGame/sgFunc.cpp:27:44: error: cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’
"\nchRace: " << chRace <<
^
In file included from /usr/include/c++/4.8/iostream:39:0,
from /home/ubuntu/workspace/saveGame/sgFunc.cpp:1: /usr/include/c++/4.8/ostream:602:5: error: initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = std::vector<int>]’
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
^
最佳答案
std::vector<>
无法(默认情况下)流式传输到字符输出流,这是您尝试使用 << chAttributes
进行的操作.您需要手动将其转换为字符串,或提供 operator<<
用于将其流式传输到字符输出流。
一个选项,如果你想写出逗号分隔的内容(你需要包括 <iterator>
和 <algorithm>
):
outputFile << "chName: " << chName <<
"\nchSex: " << chSex <<
"\nchRace: " << chRace <<
"\nchAttributes: ";
copy(chAttributes.begin(),
chAttributes.end(),
ostream_iterator<int>(outputFile, ","));
outputFile << "\nchLevel: " << chLevel <<
"\nchStage: " << chStage;
我编写此示例代码时假设 using namespace std;
正如您的代码所示。我建议不要使用这一行,而是 std::
-从 std
中确定你想使用的东西命名空间。
关于c++ - ofStream 错误 : writing to text file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41901764/