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
iostreamis used for input/output operations.vectorincludes to provide the necessary functions to work with vectors in cpp. - Declare variables
Declarento store the number of elements. Create a vector of data typeintnamedvect1to store the entered elements. - Take input from the user
Use aforloop to iteratentimes. Within each iteration, read an element from the user and store it in theelementvariable. Add theelementto thevect1using thepush_back()function. - Print the vector elements
Use anotherforloop to iterate through the vectorvect1to 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.