2D Vector Questions

Using the file called text.txt for example as command-line argument input, How would I create a file object and load the file into a 2D vector of vector<vector<char>>? Any help would be great, thanks!

Last edited on
Usually you would read the lines into a string so you would have a vector of strings.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

int main(int argc, char **argv) {
    if (argc != 2) {
        std::cerr << "Usage: filereader FILE_TO_READ\n";
        return 1;
    }

    std::ifstream ifs(argv[1]);
    if (!ifs) {
        std::cerr << "Can't open " << argv[1] << '\n';
        return 1;
    }
    
    std::vector<std::string> v;
    std::string line;
    while (getline(ifs, line))
        v.push_back(line);
    ifs.close();        

    for (auto& x: v)
        std::cout << x << '\n';

    return 0;
}

But if it must be a vector of vectors, then something like this:
1
2
3
4
5
6
7
8
9
10
11
    std::vector<std::vector<char>> v;
    std::string line;
    while (getline(ifs, line))
        v.push_back(std::vector<char>(line.begin(), line.end()));
    ifs.close();        

    for (const auto& x: v) {
        for (const auto& y: x)
            std::cout << y;
        std::cout << '\n';
    }

Topic archived. No new replies allowed.