Multidimensional array as input?

I have an assignment that asks the user to input two integer matrices and then multiplies them. The input format is:
1 2 3
4 5 6

so every space means one more column and every ENTER means one more row. Pressing ENTER after an empty line means the input is over. I am not quite sure how to implement this? Currently, I'm thinking of using while(getline(cin, str)) and checking if a char is ' ' or '\n'.
Assuming you have a matrix class:

1
2
3
4
5
struct matrix
{
  vector <vector <int> > data;
  ...
};

You should implement a stream extraction operator (a function) to read one.

1
2
3
4
istream& operator >> ( istream& ins, matrix& m )
{
  ...
}

Then you can use the function to read the user's matrices:

1
2
3
4
5
6
7
  cout << "Enter the first matrix\n"
          "  (separate column values by spaces;\n"
          "   press enter for each row; press enter twice to finish):\n";
  matrix m1, m2;
  cin >> m1;
  cout << "Enter the second matrix:\n";
  cin >> m2;

So the issue now is to do this fancy input with spaces and enters.

Read each line as a string. Quit when EOF/fail or empty line.
Use a stringstream to split each line into values:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
istream& operator >> ( istream& ins, matrix& m )
{
  string s;
  while (getline( ins, s ) and !s.empty())
  {
    m.emplace_back( vector <int> () );  // new row
    istringstream ss( s );
    int value;
    while (ss >> value)
    {
      m.back().emplace_back( value );  // add value to end of last row
    }
  }
  return ins;
}

You'll need to #include <ciso646> <iostream> <sstream> <string> and <vector>.

disclaimer: I typed this in off the top of my head, and I'm tired, so there may be an error in there.

Hope this helps.
Unfortunately, we must solve this problem with arrays.
Okay, so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
struct matrix
{
  int data[MAX_ROWS][MAX_COLUMNS];
  int rows, columns;
  ...
};

istream& operator >> ( istream& ins, matrix& m )
{
  string s;
  int row = 0;
  while (getline( ins, s ) and !s.empty() and (row < MAX_ROWS))
  {
    istringstream ss( s );
    int value;
    int column = 0;
    while ((ss >> value) and (column < MAX_COLUMNS))
    {
      m.data[ row ][ column ] = value;
      columns++;
    }
    row++;
  }
  return ins;
}

Topic archived. No new replies allowed.