tang
tang

Reputation: 33

Read from File into Struct and Add to Vector

I want to read from a text file in the following format:

1,1,1
2,2,2
3,3,3
4,4,4
5,5,5

Parse its rows into a struct:

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

And then add the structs to a vector.

I am currently using an overloaded extraction operator for istream to retrieve the numbers, like such:

//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;
}

And then I want to add those numbers straight into the vector 'stats'. This is what I have so far:

#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;
}

I tried referring to this post: Read file line by line But so far, no luck... Am I missing something, or is there a better way to implement this?

Upvotes: 0

Views: 1031

Answers (1)

user4581301
user4581301

Reputation: 33931

The data format is

1,2,3

but

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

only knows how to read numbers and cannot process the commas.

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

will consume the commas by reading them into the aptly named comma.

Upvotes: 2

Related Questions