c++stringvectorchar2d-vector

How do I read a text file into a 2D vector?


I have to read a text file which has rows and columns into a vector. The text file could be of any size. One example of text file:

T,T,T,F,T
T,T,T,T,T
T,T,T,T,T
T,T,T,T,T
T,T,T,T,T
T,T,T,T,T
T,T,T,T,T

Now, how do I upload this text file on to a 2D vector?

so far, I know I have to use a vector of vectors (2d vector) and so I initialized it like this:

vector<vector<char> > forest;

I don't know how to move forward from here. I would assume I must use a nested for loop but I don't have much practice with 2d vectors.

I also was thinking about using getline and reading each line as a string or using the .get function and treat each character as a char within a while loop?


Solution

  • You can use getline to read the file line by line into strings. For each string you read, iterate over its characters to build row vectors to populate your forest:

    #include <fstream>
    #include <iostream>
    #include <string>
    #include <vector>
    
    int main() {
        std::string line;
        std::ifstream infile("file.txt");
        std::vector<std::vector<char> > forest;
    
        while (std::getline(infile, line)) {
            std::vector<char> row;
    
            for (char &c : line) {
                if (c != ',') {
                    row.push_back(c);
                }
            }
    
            forest.push_back(row);
        }
    
        for (std::vector<char> &row : forest) {
            for (char &c : row) {
                std::cout << c << ' ';
            }
    
            std::cout << '\n';
        }
    
        return 0;
    }
    

    Output:

    T T T F T
    T T T T T
    T T T T T
    T T T T T
    T T T T T
    T T T T T
    T T T T T