How to take user input into vector

In this tutorial, we will learn how to obtain user input and store it in a vector in CPP. It will ask the user the number of elements they want to store and then the elements. The elements the user enters will be stored in a vector, which acts like a ‘dynamic- array’ that can change its size during the program’s execution.

Take user input into a vector.

Let’s learn this with a simple approach.

Table of Contents :


  • Explanation
  • Code
  • Output
  • Summary

Explanation :


  •  Include necessary header files
    iostream is used for input/output operations. vector includes to provide the necessary functions to work with vectors in cpp.
  •  Declare variables
    Declare  n to store the number of elements. Create a vector of data type int named vect1  to store the entered elements.
  •  Take input from the user
    Use a for loop to iterate n times.  Within each iteration, read an element from the user and store it in the element variable.  Add the element to the vect1 using the push_back() function.
  • Print the vector elements
    Use another for loop to iterate through the vector vect1  to display the elements.

Code :


#include <iostream> 
#include <vector> 
using namespace std;

int main()
{
    vector<int>vect1; 
    int element, n; 
    cout<<"Enter the size of vector:"<<endl; 
    cin>>n;
    
    for(int i=0; i<n; i++) { 
        cout<<"Enter an element to add to this vector: "; 
        cin>>element; 
        vect1.push_back(element); 
    }
    
    cout<<"The elements of vector are : "<<endl; 
    for(int i=0; i<vect1.size(); i++){ 
        cout<<vect1[i]<<" "; 
    }

    return 0;
}

Output :


After successfully compiling and running the above code, the output will be:

Enter the size of vector: 
4
Enter an element to add to this vector: 5
Enter an element to add to this vector: 9
Enter an element to add to this vector: 2
Enter an element to add to this vector: 6
Elements of vector are : 
5 9 2 6

Summary :

This code effectively takes user input and stores it in a vector. It depicts the use of input and output operations to interact with the user.

 

Leave a Comment

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

Scroll to Top