Reputation: 25
So I have this function that writes to a text file but I keep getting this error that has something to do with the syntax of outputting using ofstream I believe. Can someone help diagnose this for me?
Thanks,
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;
}
Running /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)
^
Upvotes: 1
Views: 260
Reputation: 168988
std::vector<>
can't be streamed (by default) to a character output stream, which is what you are trying to do with << chAttributes
. You need to manually convert it to a string, or provide an operator<<
for streaming it to a character output stream.
One option, if you want to write out the contents comma-delimited (you need to include <iterator>
and <algorithm>
):
outputFile << "chName: " << chName <<
"\nchSex: " << chSex <<
"\nchRace: " << chRace <<
"\nchAttributes: ";
copy(chAttributes.begin(),
chAttributes.end(),
ostream_iterator<int>(outputFile, ","));
outputFile << "\nchLevel: " << chLevel <<
"\nchStage: " << chStage;
I wrote this example code assuming using namespace std;
as your code appears to. I would advise against using this line, and instead std::
-qualify stuff you want to use from the std
namespace.
Upvotes: 5