Take user input into vector in C++

In this tutorial, we will get an idea about how to take user input into vector in C++. But before knowing this, we expect that you have some basic idea about the array. As we know that vectors are dynamic arrays which means they can grow and shrink their size according to use. So here we will see the different ways of taking input from the user into vector. We will also learn to take input in a 2D vector. But first, we will learn to take input into a 1D vector from the user.

Different ways of taking input into 1D vector in C++

Example code 1 :

The basic way is if the user will give the size of the vector then we can take input into vector simply using for loop. See the code below to understand it better.

Input: 5
       2 9 4 7 2
#include<bits/stdc++.h>
using namespace std;

//main function
int main() {
    int n; 
    cin>>n; // taking size of vector from user
    int a;
    vector<int> v;
    // we can also mention size here like
    // vector<int> v(n);
    for(int i=0 ; i<n ; i++)
    {
        cin>>a;
        v.push_back(a);
    }
    for(auto &p : v)
    {
        cout<<p<<" ";
    }
    cout<<endl;
    return 0;
}
Output:2 9 4 7 2

Example code 2 :  

If the user will not enter the size of the vector but the user wants to enter vector elements as much as they want. So here we will learn how to code it.

Input : 3 9 1 72 3 5 2

#include<bits/stdc++.h>
using namespace std;

//main function
int main() {
   int a;
   vector<int> v;
   // user can add element as much as they want
   while(cin>>a)
   { 
       v.push_back(a);
   }
   for(auto &p : v)
   {
      cout<<p<<" ";
   }
   cout<<endl;
   return 0;
}
Output: 3 9 1 72 3 5 2

Take user input into 2D vector in C++

In a 2D vector, we require the size of row and column from the user but the column size can be different for each row of vector which was not possible in the case of an array. So it has its own benefit in the case when we want to enter different numbers of values in a different row. So let’s learn it using this example code written below.

Input:2
      2
      2 4
      5
      2 5 6 6 4
#include<bits/stdc++.h>
using namespace std;

//main function
int main() {
    vector<vector<int>> v;
    int row, column, a;
    cin>>row;
    // taking input into 2D vector from user
    for(int i=0 ; i<row ; i++) {
         cin>>column;
         vector<int> p;
         for(int j=0 ; j<column ; j++) {
              cin>>a;
              p.push_back(a);
         }
         v.push_back(p);
    }
    // displaying 2D vector value
    for(auto q: v) {
        for(auto it: q) {
            cout<<it<<" ";
         } 
         cout<<endl;
     }
      return 0;
Output: 2 4
        2 5 6 6 4

 

Also read: How to break out of nested loops in C++

Leave a Reply

Your email address will not be published. Required fields are marked *