I've been trying to read sequences of numbers from a file to a 2D vector without significant success.
Data in sequences.txt
1,2,3,4,5
6,3,1
7,4,10,4,1,9
I've encountered with few problems, reading sequences of numbers of an unknown length (format). For example if it was fixed a 3 number format, input would look like this:
input_stream >> integer >> char >> integer >> char >> integer
But the number of numbers of each sequence is unknown...
Another problem is the ','
char, it isn't located at the end of each sequence, meaning that somehow I would have go through the line right to the very last number in a sequence, then pick it up after I finish going through the line, is that possible?
My attempt of code:
#include <fstream>
#include <iostream>
#include <vector>
void PrintMatrix(std::vector<std::vector<int>> matrix)
{
for(auto v : matrix)
{
for(auto x : v)
{
std::cout << x << " ";
}
std::cout << std::endl;
}
}
int main()
{
std::fstream input_stream("sequences.txt", std::ios::in);
if(!input_stream)
std::cout << "Problem with opening a file";
else
{
std::vector<std::vector<int>> matrix;
while(input_stream.good())
{
std::vector<int> v;
int number;
char chr;
while(input_stream >> number >> chr)
{
v.push_back(number);
}
matrix.push_back(v);
}
PrintMatrix(matrix);
}
return 0;
}
I started learning files very recently, I read most of the literature and now trying to practice, so any tips on how to solve this problem or any tips on working with files in general, I'd be very grateful :)
Thanks
P.S.
Output that I get from this code (which is wrong): 1 2 3 4 5
Output I want to get:
1 2 3 4 5
6 3 1
7 4 10 4 1 9