【问题标题】:ofStream error: writing to text file?ofStream 错误:写入文本文件?
【发布时间】:2017-01-27 19:38:32
【问题描述】:

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

【问题讨论】:

  • 除非您为vectors 重新定义了&lt;&lt; 运算符,否则您不能简单地执行&lt;&lt; chAttributes

标签: c++ file io output ofstream


【解决方案1】:

std::vector&lt;&gt; 不能流式传输(默认情况下)到字符输出流,这是您尝试对 &lt;&lt; chAttributes 执行的操作。您需要手动将其转换为字符串,或提供operator&lt;&lt; 以将其流式传输到字符输出流。

一个选项,如果你想写出逗号分隔的内容(你需要包括&lt;iterator&gt;和&lt;algorithm&gt;):

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::-qualify 来从 std 命名空间中使用您想要使用的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多