0

I have a .dat file containing full of integers 100 by 100, and I am trying to transfer x rows and x columns into a new vector, I've managed to ge the first row with the desired columns but stuck in trying to get to the next line and until to the x rows, please give help. also some help on the display part, I'm not sure how to display a vector with more than one rows and columns. Tried data.at(i).at(j) double for loop but unsuccessful

//variable
int row, col;
string fname;
ifstream file;
vector<vector<int>> data;

//input
cout << "Enter the number of rows in the map: ";    cin >> row;
cout << "Enter the number of columns in the map: "; cin >> col;
cout << "Enter the file name to write: ";           cin >> fname;

//open file
file.open(fname, ios::in);  //  map-input-100-100.dat map-input-480-480.dat

//copy specified data into vector
int count = 0, temp = 0;
string line;
while (count < row)
{
    for (int i = 0; i < col; ++i)
    {
        file >> temp;
        data[count].push_back(temp);
    }
    ++count;
    getline(file, line);
    stringstream ss(line);

}

//output
for (int i = 0; i < data.size(); i++)
{
    for (int j = 0; j < data[i].size(); j++)    cout << data[i][j] << ' ';
    cout << endl;
}

This is my code so far

rrc
  • 275
  • 1
  • 3
  • 7

1 Answers1

0

Tried locally with file like this:

12 34 42 53
32 45 46 47
31 32 33 34

and the reading has to be changed (you don't have any parsing of line in your code). Working example follows:

//copy specified data into vector
string line;
int i, j, offset, int_val;
size_t tmp;
i = 0;
while( file.good() && (i<row) ){
  getline( file, line );
  //create one line in data
  data.push_back( vector<int>(0) );
  offset = 0;
  j = 0;
  //parse one line
  while( 1 ){
    try{
      int_val = stoi( line.substr(offset), &tmp );
    }catch( const exception& e){
      //ending loop when no more numbers available
      ++i;
      break;
    }
    //exiting loop when reqiuered limit reached
    if( j >= col ){
      ++i;
      break;
    }
    //save to vector
    data[i].push_back( int_val );
    offset += tmp;
    ++j;
  }
}
file.close();     //don't forget to close the file

printing output seems to be OK

Kajienk
  • 111
  • 1
  • 4