#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <vector>
usingnamespace std;
using matrix = vector< vector<int> >;
//==========================================================
matrix readArray( string filename )
{
matrix M;
ifstream in( filename );
string line;
while ( getline( in, line ) ) // read a whole line of the file
{
stringstream ss( line ); // put it in a stringstream (internal stream)
vector<int> row;
int item;
while ( ss >> item ) row.push_back( item ); // read all available items on this line
if ( !row.empty() ) M.push_back( row ); // add non-empty rows to matrix
}
return M;
}
//==========================================================
void write( const matrix &M )
{
constint w = 4;
for ( auto row : M )
{
for ( auto e : row ) cout << setw( w ) << e << ' ';
cout << '\n';
}
}
//==========================================================
int main()
{
matrix M = readArray( "data.txt" );
write( M );
}
//==========================================================
1 2 3
4 5 6
For the palooka-code version you could overload lots of << and >> operators:
Exactly the same way you have the 1D row vector. Three numbers is three numbers.
How you use the vector makes the difference:
1 2 3 4 5 6 7 8
std::vector<int> V;
// print as column
for ( auto elem : V ) std::cout << elem << '\n';
// print as row
for ( auto elem : V ) std::cout << elem << ' ';
std::cout << '\n';