0

I'm struggling on overloading the ifstream operator to get an input from a file in a matrix form and creating a 2D array. This is for a 3x3 matrix. This is a small part of an assignment without which my whole assignment is quite pointless.

file example:

1 2 3
4 5 6
7 8 6
lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75

1 Answers1

1

I have done this way...

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
  int data[3][3];
  int i = 0;
  int j = 0;
  ifstream in(filename);
  std::string line;
  std::string temp;
  while(std::getline(in, line))
  {
      std::istringstream iss(line);

      // Parse each line using the input string stream
      j = 0;
      while(std::getline(iss,temp,' '))
      {
         data[i][j] = std::stoi(temp);
         j++;
      }
      i++;
  }
  return 0;
}
lakshmen
  • 28,346
  • 66
  • 178
  • 276