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'.
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.