0

I want to store the content of .txt file in a 2D array. I am a beginner in c++ and I don't know how to do that.

So, currently, I can read from a file and display it content. Moreover, I can store in a buffer (std::string)

This is my code :

#include <iostream>
#include <fstream>

int main( int argc, char* argv[] )
{
    std::ifstream inFile;

    inFile.open(argv[1]);
    if(!inFile) {
        std::cout << "Unable to open file: " << argv[1] << std::endl;
        return -1;
    } else { 
        std::string str((std::istreambuf_iterator<char>(inFile)),
              std::istreambuf_iterator<char>());
        std::cout << str;
        inFile.close();
}
    return 0;
}

My .txt file looks like that

cat file.txt

----------
|        |
|        |
|        |
|        |
----------

So, can you help to find the best way to store my file in a 2D array ? Do you know what is the best way to do that ?

Thank you for answers

1
  • Do you want each word in your lines to be tokenized? Why do you exactly want to store them in a 2D array? If not (as i see from file.txt), you can think of each string in your vector as the second dimension, since you can reach each character in it. Commented Apr 10, 2021 at 16:39

1 Answer 1

3

So you want a vector of chars that is 2D, correct? That, expanded, is a vector of vectors of chars

My approach would be this:

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

int main(int argc, char* argv[])
{
    std::ifstream inFile;

    inFile.open(argv[1]);
    if (!inFile) {
        std::cout << "Unable to open file: " << argv[1] << std::endl;
        return -1;
    }
    
    std::string line;
    std::vector<std::vector<char>>lines;

    while (std::getline(inFile, line)) { //while there still are lines in inFile, put one into line

        std::vector<char> chars;

        for (int i = 0; i < line.size(); ++i) {
            chars.push_back(line[i]); //put every char of line into chars
        }
        lines.push_back(chars); //put the vector of chars into the vector of vectors of chars
    }

    //when you reach here, you have a vector of vectors of chars

    char curr = lines[1][1]; //You can access a member like this.

    inFile.close();
    return 0;
}

This is simpler than using streambufs and streambuf_iterators, I think.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.