1

I have file that contains

Name    Age     FavSport
Michael, "18,0" , "Soc,cer", Cricket, Hockey
John, "18,0", Cricket
Mitchell, "19,0", Soccer, "Hoc,key"

I am trying to read it into vector of class objects

#include <string>
#include <vector>
#include <fstream>

class Student {
    public:
    std::string name;
    int age;
    std::vector<std::string> favSport;
};

class Team {
    public:
    std::vector<Student> teamVec;
};

When I try to split file by comma it splits commas between quotation like 18,0 it think 18 and 0 separate and gives me error. Also same for Soc,cer, it thinks they are seperate. How can i tell program not to split between quotation. Can any please have a look at code and tell me where i can edit or edit for me please thank you (I can't use stringstream since i havn't been to that chapter yet, what I have coded is kind of knowledge I know)

int main() {
    std::string line;
    std::vector<std::string> teamVec;
    std::ifstream myfile("team.txt");
    if (!myfile)
    {
        std::cout << "Error" << std::endl;
        return -1;
    }
    bool firstLine = true;
    Team myTeam;
    while (std::getline(myfile, line))
    {
        if(firstLine) {
            firstLine = false;
        } else {
            Student temp;
            int times = 0;
            size_t pos = 0;
            std::string token;
            while ((pos = line.find(',')) != std::string::npos) {
                token = line.substr(0, pos);
                times++;
                if(times == 1) {
                    temp.name = token.substr(1,token.size()-2);
                } else if(times == 2) {
                    temp.age = stoi(token);
                } else {
                    temp.favSport.push_back(token);
                }
                std::cout << token << std::endl;
                line.erase(0, pos + 2);
            }
            temp.favSport.push_back(line);
            myTeam.teamVec.push_back(temp);
        }
    }
    // USE myTeam
    return 0;
}
KarateKing
  • 35
  • 4
  • I would use `strcspn(str, "\",");` which will find either occurence, which cames first, instead of find. – Devolus Apr 14 '21 at 08:45
  • @Devolus You can have the same effect without C functions: [`find_first_of`](https://en.cppreference.com/w/cpp/string/basic_string/find_first_of) – Yksisarvinen Apr 14 '21 at 08:50
  • I was wondering about `age`, you are conveting it to `int`, why does it have decimal places in the file? – anastaciu Apr 14 '21 at 08:54
  • @anastaciu i just realised I will convert now to double, the file is kind of weirdly written hence i am having some difficulties reading into objects. – KarateKing Apr 14 '21 at 08:58
  • 1
    [csv parser?](https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c) – user1810087 Apr 14 '21 at 08:59

0 Answers0