you can't.
math being what it is, 2*4 is 8, and your file appears to have much more than 8 numbers.
say the file actually had 8 values, though, or the first 8 were what belonged in the array in the right order. Because you used a solid block 2d array, you can collapse it to one-d and do it with simple code.
int *ip = &array[0][0];
for(int i = 0; i < 8; i++) //8 is 2*4;
{
filevar>>ip[i];
}
if you need a flexible sized 2-d construct, you need to re-do with vectors. Vectors do not collapse this way, you can either make a 1-d and fake the 2-d access or you have to double loop and deal with the problems caused by multi dimensions.
// Read a table into a vector of vector
// • All elements are the same type
// • Elements are separated by spaces
// • No element is missing/empty
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
template <typename T>
std::vector <std::vector <T>>
read_table_of( std::istream& ins )
{
std::vector <std::vector <T>> result;
std::string s;
while (getline( ins, s ))
{
std::vector <T> row;
std::istringstream ss( s );
T value;
while (ss >> value) row.emplace_back( value );
result.emplace_back( row );
}
return result;
}
// A simple example to run
#include <sstream>
#include <utility>
int main()
{
std::istringstream input(
"1 2 3\n""4 5 6\n""7 8 9\n"
);
auto table = read_table_of <int> ( input );
for (auto record : table)
{
for (auto field : record)
std::cout << field << " ";
std::cout << "\n";
}
}
It depends on his exact input. He shows a comma at the end of the line as well as between values. If that last comma isn't there, then the above simple solution will "eat" the first digit of the first number on the next line.
Some combination of our two approaches might be best. And combining with Duthomhas's approach allows any number of lines and even different numbers of values-per-line.