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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <vector>
#include <string>
#include <iostream>
using namespace 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...
        }
    }
}


I hope I have presented my problem clearly..
Last edited on
Do you have to use vectors as a part of the assignment?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
using namespace 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>
using namespace 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';
   }
}
Last edited on
Topic archived. No new replies allowed.