Home > Software engineering >  How to separate strings into 2D vector in C ?
How to separate strings into 2D vector in C ?

Time:06-19

So this is the file that data that I'm reading from:

MATH201,Discrete Mathematics
CSCI300,Introduction to Algorithms,CSCI200,MATH201
CSCI350,Operating Systems,CSCI300
CSCI101,Introduction to Programming in C  ,CSCI100
CSCI100,Introduction to Computer Science
CSCI301,Advanced Programming in C  ,CSCI101
CSCI400,Large Software Development,CSCI301,CSCI350
CSCI200,Data Structures,CSCI101

I have successfully read from the file and stored this information in a 2D Vector, but when I check the size of specific rows using course.info[x].size() it appears that its only counting the strings that have spaces between them. So for example, course.info[2].size() returns 2, whereas I would rather it would return 3. Essentially I want it to count each bit of information that is separated by a comma instead of a space. If I use while (getline(courses, line, ',') it puts the information separated by a comma in their own row, which is not what I want.

void LoadFile() {
vector<vector<string>> courseInfo;


ifstream courses;
courses.open("CourseInfo.txt");

if (!courses.is_open()) {
    cout << "Error opening file";
}

if (courses) {
    string line;

    while (getline(courses, line)) {
        courseInfo.push_back(vector<string>());

        stringstream split(line);
        string value;

        while (split >> value) {
            courseInfo.back().push_back(value);
        }
    }
}

for (int i = 0; i < courseInfo.size(); i  ) {
    for (int j = 0; j < courseInfo[i].size(); j  )
        std::cout << courseInfo[i][j] << ' ';

    std::cout << '\n';
}

CodePudding user response:

getline(.., .., ',') is the tool for the job, but you need to use it in a different place.

Replace while (split >> value) with while (getline(split, value, ',').

  • Related