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 <fstream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::string filname="data/file01.txt";
std::ifstream file01(filname);
std::vector<std::vector<int>> v;
std::string line;
while(getline(file01,line))
{
std::stringstream ls;
ls<<line;
int c;
std::vector<int> t;
while(!ls.eof())
{
ls>>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)?
nested_vector[x][y]
unless you knownested_vector[x]
has at leasty
elements -and this information is contained in liney-1
. That means you could as well store lines by pair and elide the first line's last number since it ispair_of_lines.size() - 1
. Actually, if the numbers are all one-digit long, you don't need to convert thechar
s to integers, and you can store the pairs of lines directly as strings. You could even simply store the whole file as a long string ... (1/2) \$\endgroup\$