#include <vector>
#include <string>
#include <iostream>
usingnamespace std;
int main(){
vector<vector<int>> container{{-1,-1,-1},{-1,-1,-1},{-1,-1,-1}};
string userInput;
cout <<"Please input nine numbers from 0-9 with spaces in between each of them: ";
getline(cin,userInput);
//The input should look similar to this "1 2 3 4 56 7 8 9 120", which has nine numbers.
//I am stuck here.
//I want to read each nine numbers from userInput.
//I would read '11' as one number and '1 1' as two numbers.
for( int row=0; row<3; row ++ ){
for( int column=0; column<3; column++ ){
//Populate 2D vector here...
}
}
}
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
usingnamespace std;
int main()
{
vector< vector<int> > container( 3, vector<int>( 3, -1 ) );
string userInput;
cout << "Please input nine numbers from 0-9 with spaces in between each of them: ";
getline( cin, userInput );
stringstream ss( userInput );
for ( auto &row : container )
for ( int &i : row ) ss >> i;
for( auto &row : container )
{
for( int i : row ) cout << i << '\t';
cout << '\n';
}
}
Please input nine numbers from 0-9 with spaces in between each of them: 1 2 3 4 56 7 8 9 120
1 2 3
4 56 7
8 9 120
To be fair, you could also do it the easy way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <vector>
#include <iostream>
usingnamespace std;
int main()
{
vector< vector<int> > container( 3, vector<int>( 3, -1 ) );
string userInput;
cout << "Please input nine numbers from 0-9 with spaces in between each of them: ";
for ( auto &row : container )
for ( int &i : row ) cin >> i;
for( auto &row : container )
{
for( int i : row ) cout << i << '\t';
cout << '\n';
}
}