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