K. Nyguen K. Nyguen - 2 months ago 20
C++ Question

Reading in a .csv file and storing values into vector and struct c++

I am new to programming in C++ and am trying to do a practice problem, but I don't really understand what it is trying to get me to do since a vector can only hold one data type (unless it can hold more):

Read in a .csv file where each line is structured as such: "username,gpa,age". Store these values into a struct with username, gpa, and age (string,float,int) and create a list as a vector. As you read in each line, insert into the vector list sorted by username. Then loop through and print out the list formatted as : "username [gpa] age:#" e.g., "mark [3.9] age:19" and also write the output to a file (using C++, not Unix).

Am I supposed to put all of those values into the same vector as separate data types or keep them all together in a string and then insert them? How do I store these values into a struct? If someone can tell me how they would solve the question and give me some sample code that'd be great, thank you.


Ok, by the sound of it, the question wants you to read the file, put the information into a struct, then insert the structs into the vector in alphabetical order according to the name.

I'd make the struct something like:

struct StudentInfo {
    string name;
    string gpa;
    string age;
} StudentInfo;

I'd then open the file and read the whole thing into a string. Then I'd read through the string, tokenizing it by newline character. As I get each string, I'd put it into a function that parsed it and returned a struct studentInfo. then insert the struct into the vector.

An example of how the parsing function might work:

struct StudentInfo parseData(string iStr) {
    struct StudentInfo info;
    size_t subStrStart = 0;
    size_t subStrEnd = 0;
    subStrEnd = iStr.find(',', subStrEnd);
    info.name = iStr.substr(subStrStart, subStrStart - subStrEnd);

    subStrStart = subStrEnd;
    subStrEnd = iStr.find(',', subStrEnd+1);
    info.gpa = iStr.substr(subStrStart, subStrStart - subStrEnd);

    subStrStart = subStrEnd;
    subStrEnd = iStr.find(',', subStrEnd+1);
    info.age = iStr.substr(subStrStart, subStrStart - subStrEnd);

    return info;

Some pseudocode for the main function I'd make:

vector<struct StudentInfo> infoVec;
string fileStr = read(filename.csv); // make an ifstream or something similar
string lineStr;
size_t subStrEnd = 0;
size_t subStrStart = 0;
while (subStrEnd < fileStr.Size) {
    subStrEnd = iStr.find('\n', subStrEnd); //alternatively use std::getline() directly on the file stream
    lineStr = iStr.substr(subStrStart, subStrStart - subStrEnd);
    subStrStart = subStrEnd;
sortByName(infoVec) // User defined function
printInfoVec(infoVec) // User defined function

The print function and the sort function are pretty self explanatory, they'd require you to write them though.