c++ - ofStream 错误 : writing to text file?

标签 c++ file io output ofstream

所以我有这个写入文本文件的函数,但我一直收到这个错误,我相信这与使用 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/

相关文章:

asp.net - 如何获取文件的输入类型以在 ASP.NET 中选择时自动回发

c - 如何使用C程序检测文件中的特定字符串

python - 写入文件,多个小字符串与一个大字符串

c++ - 试图制作一个排序的动态列表(数据结构)

当第二个元素是 X 时,C++ Map 获取第一个元素

linux - 如何在 linux 的 split 命令中设置起始索引?

c++ - 异步 IO 的整洁代码

c++ - 为什么我不能为 std::vector 元素取别名?

c++ - 如何从父模板函数访问子成员?

java - 网络/数据库作业的足够线程数