Read integers from coupled lines in a text file I'm trying to read a text file formatted as in this example:

5 3
3 1 5
6 6
6 1 3 2 5 4


Where the lines are coupled, with the line above always being of length equal to 2 and the line below having length equal to the the last digit in the line above.

(Unfortunately this is from an old note I took and I don't remember what those numbers are actually supposed to mean, so I'm limiting myself to store them in a multidimensional vector form where they can be easily recovered).

In the beginning I was tring to read the digit which represents the length below to execute a loop of finite length, but in the end this is the code I wrote:

#include &lt;fstream&gt;
#include &lt;sstream&gt;
#include &lt;string&gt;
#include &lt;vector&gt;
int main()
{
    std::string filname="data/file01.txt";
    std::ifstream file01(filname);
    std::vector&lt;std::vector&lt;int&gt;&gt; v;
    std::string line;
    while(getline(file01,line))
    {
        std::stringstream ls;
        ls&lt;&lt;line;
        int c;
        std::vector&lt;int&gt; t;
        while(!ls.eof())
        {
            ls&gt;&gt;c;
            t.push_back(c);
        }
        v.push_back(t);
    }
    return 0;
}


This gives me a 2-dimensional vector that can be easily accessed, but I don't like having to convert both the file and each string to a stream and I don't like using nested vectors.

Is there a way to achieve this goal with more simple and elegant code (even if it means to make the code more specific)?
You're turning the whole input file into a vector of vectors. That's fine, but you state yourself that your input has structure. It would be nice to have that structure reflected in your program:


since the lines are couple in pairs I'd like to see a code block that clearly processes a pair of lines
you should then eliminate the redundancy that the second number of the 1 st line equals the number of items on the second.