我想将 vector v 的内容写入文件。问题是不是内容而是地址将被放置在文本文件中。
当我用 *pos 代替 &pos 我得到错误:error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'entry'
它是如何正确工作的?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>
/*
Data.txt
John
6543
23
Max
342
2
A Team
5645
23
*/
struct entry
{
// passengers data
std::string name;
int weight; // kg
std::string group_code;
};
void reservations(std::vector<entry> v)
{
std::ofstream outfile;
outfile.clear();
outfile.open("reservations.txt");
// print data in vector
std::vector<entry>::iterator pos;
for (pos = v.begin(); pos!= v.end();++pos)
{
outfile << &pos << std::endl;
std::cout << &pos << std::endl;
}
outfile.close();
}
entry read_passenger(std::ifstream &stream_in)
{
entry passenger;
if (stream_in)
{
std::getline(stream_in, passenger.name);
stream_in >> passenger.weight;
stream_in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(stream_in, passenger.group_code);
stream_in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return passenger;
}
return passenger;
}
int main(void)
{
std::ifstream stream_in("data.txt");
std::vector<entry> v; // contains the reservations
std::vector<entry> a; // contains the cancellations
const int limit_total_weight = 10000; // kg
int total_weight = 0; // kg
entry current;
while (stream_in)
{
current = read_passenger(stream_in);
if (total_weight + current.weight >= limit_total_weight)
{
// push data (cancellations) to vector
a.push_back(current);
}
else
{
total_weight = total_weight + current.weight;
// push data (reservations) to vector
v.push_back(current);
}
}
reservations(v); // write reservations to file
std::cout << "Rest " << limit_total_weight - total_weight << "kg" <<std::endl;
return 0;
}
最佳答案
你应该重载 operator <<
对于 entry
:
std::ostream& operator << (std::ostream& o, const entry& e)
{
return o << e.name
<< " " << e.weight
<< " " << e.gruop_code;
}
现在你可以写:
outfile << *pos << std::endl;
std::cout << *pos << std::endl;
关于将 vector 数据写入文件的C++问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7360068/