### How to extract integers from user input?

I am asking the user to input some numbers in one attempt, using getline().

However, I am stuck at extracting each number and putting them into 2D vector<int>.

 ``12345678910111213141516171819202122`` ``````#include #include #include using namespace std; int main(){ vector> 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... } } }``````

I hope I have presented my problem clearly..
Last edited on
Do you have to use vectors as a part of the assignment?
 ``12345678910111213141516171819202122`` ``````#include #include #include #include using namespace std; int main() { vector< vector > container( 3, vector( 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:
 ``123456789101112131415161718`` ``````#include #include using namespace std; int main() { vector< vector > container( 3, vector( 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'; } }``````
Last edited on
Topic archived. No new replies allowed.