You don't need to know how many lines are in your file or how many numbers are in each line.
Use std::vector< std::vector< int > > to store data.
If in each line, integers are separated with a space, you can iterate a string of integers and add them one by one to a vector:
#include <iostream>
#include <string>
#include <stream>
#include <vector>
using namespace std;
int main()
{
string textLine = "";
ifstream MyReadFile("filename.txt");
vector<vector<int>> main_vec;
// Use a while loop together with the getline() function to read the file line by line
while (getline(MyReadFile, textLine)) {
vector<int> temp_vec; // Holdes the numbers in a signle line
int number = 0;
for (int i = 0, SIZE = textLine.size(); i < SIZE; i++) {
if (isdigit(textLine[i])) {
number = number * 10 + (textLine[i] - '0');
}
else { // It's a space character. One number was found:
temp_vec.push_back(number);
number = 0; // reset for the next number
}
}
temp_vec.push_back(number); // Also add the last number of this line.
main_vec.push_back(temp_vec);
}
MyReadFile.close();
// Print Result:
for (const auto& line_iterator : main_vec) {
for (const auto& number_iterator : line_iterator) {
cout << number_iterator << " ";
}
cout << endl;
}
}
Hint: This code works for only integers. For floats, you can easily identify the indices of spaces in each line, get substring of your textLine, and then convert this substring to a float number .