从文件读入结构并添加到矢量

时间:2017-09-14 22:12:51

标签: c++ vector struct file-io fstream

我想以下列格式从文本文件中读取:

//Where the loaded data goes
struct process_stats{
    int process_number  = UNINITIALIZED;
    int start_time      = UNINITIALIZED;
    int cpu_time        = UNINITIALIZED;
};

将其行解析为结构:

//Operator to read from file into struct and then add to vector
std::istream& operator>>(std::istream& is, process_stats& nums)
{     
    is >> nums.process_number >> nums.start_time >> nums.cpu_time;
    return is;
}

然后将结构添加到向量中。

我目前正在使用istream的重载提取运算符来检索数字,例如:

#include <fstream>
#include <iostream>
#include <vector>
#include <iterator>
#include "Utilities.h"

//Vector to hold process_stats structs
std::vector<process_stats> stats;

//Operator to read from file into struct and then add to vector
std::istream& operator>>(std::istream& is, process_stats& nums)
{
    char comma;

    is >> nums.process_number >> comma >> nums.start_time >> comma >> 
        nums.cpu_time;

    return is;
}

//Loads data from file into process_stats struct, which is then added to 
//vector stats
int loadData(const char* filename)
{
    //Result to be returned:
    //  SUCCESS - file successfully opened,
    //  COULD_NOT_OPEN_FILE - file could not be opened.
    int result;

    std::fstream inFile(filename);

    //Check if file is open - grab data
    if(inFile)
    {
         std::copy(std::istream_iterator<process_stats>(inFile),
                    std::istream_iterator<process_stats>(),
                    std::back_inserter(stats));

          inFile.close();
          result = SUCCESS;
    }

    //Could not open file
    else
    {
        result = COULD_NOT_OPEN_FILE;
    }

    return result;
}

然后我想将这些数字直接添加到矢量&#39;统计数据中。这就是我到目前为止所做的:

{{1}}

我试着参考这篇文章:Read file line by line 但到目前为止,没有运气......我错过了一些东西,还是有更好的方法来实现它?

1 个答案:

答案 0 :(得分:2)

数据格式为

1,2,3

但是

is >> nums.process_number >> nums.start_time >> nums.cpu_time;

只知道如何读取数字,不能处理逗号。

char comma;
is >> nums.process_number >> comma >> 
      nums.start_time >> comma >> 
      nums.cpu_time;

将通过将逗号读入恰当命名的comma

来使用逗号