0

I've the need of read a txt file that is structured in this way

0,2,P,B
1,3,K,W
4,6,N,B
etc.

Now I need to read in an array like arr[X][4]
The problem is that I don't know the number of lines inside this file.
In addition I'd need 2 integers and 2 char from it...

I think I can read it with this sample of code

ifstream f("file.txt");
while(f.good()) {
  getline(f, bu[a], ',');
}

obviusly this only shows you what I think I can use....but I'm open to any advice

thx in advance and sry for my eng

1 Answer 1

5

Define a simple struct to represent a single line in the file and use a vector of those structs. Using a vector avoids having to manage dynamic allocation explicitly and will grow as required.

For example:

struct my_line
{
    int first_number;
    int second_number;
    char first_char;
    char second_char;

    // Default copy constructor and assignment operator
    // are correct.
};

std::vector<my_line> lines_from_file;

Read the lines in full and then split them as the posted code would allow 5 comma separated fields on a line for example, when only 4 is expected:

std::string line;
while (std::getline(f, line))
{
    // Process 'line' and construct a new 'my_line' instance
    // if 'line' was in a valid format.
    struct my_line current_line;

    // There are several options for reading formatted text:
    //  - std::sscanf()
    //  - boost::split()
    //  - istringstream
    //
    if (4 == std::sscanf(line.c_str(),
                         "%d,%d,%c,%c",
                         &current_line.first_number,
                         &current_line.second_number,
                         &current_line.first_char,
                         &current_line.second_char))
    {
        // Append.
        lines_from_file.push_back(current_line);
    }

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

1 Comment

ty @hmjd this is exactly what I'm looking for. I was thinking abuot struct but I didn't know how to integrate it into vectors^

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.