ofStream错误:写入文本文件?

时间:2017-01-27 19:38:32

标签: c++ file io output ofstream

所以我有这个函数写入文本文件,但我一直得到这个错误,这与使用ofstream输出语法有关。我相信。 有人可以帮我诊断一下吗?

谢谢,

Evin

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)
     ^

1 个答案:

答案 0 :(得分:5)

无法将

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命名空间中限定要使用的内容。