将 vector 数据写入文件的C++问题

标签 c++ text-files

我想将 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/

相关文章:

c++ - opencv sgbm 在对象边缘产生异常值

java - 安卓/java : String url does not work in HttpGet(url)

c# - 将 Xml 转换为 txt

c++ - 库依赖项 "forwarding"或部分静态库?

c++ - 窗口中出现 glTexImage2D 切片和对齐问题

c++ - 以低权限枚举 Windows 上的共享文件夹

Matlab:如何通过指定 header 名称读取和提取矩阵?

c - 打印到 C 中的文件

c++ - 当数据包含空格时,如何将制表符分隔文件的内容加载到 C++ 中的二维字符串 vector 中?

c++ - 模板特化的不同编译器行为