Take Multiple Inputs from a User in C++
To take multiple inputs from users, we can repeatedly use the std::cin using loops. It will allow the user to enter the data till required. We can use any data container to store the data entered by the user.
C++ Program to Take Multiple Inputs from User
The below example demonstrates how we can take multiple inputs from a user in C++.
C++
// C++ program to input multiple items #include <iostream> #include <vector> using namespace std; int main() { int n; // Input the number of elements cout << "Enter the number of elements you want to " "input: " ; cin >> n; // Initialize a vector of size n vector< int > vec(n); // Input n numbers into the vector cout << "Enter " << n << " numbers: " ; for ( int i = 0; i < n; i++) { cin >> vec[i]; } // Output the entered numbers cout << "You entered: " ; for ( int i : vec) { cout << i << " " ; } cout << endl; return 0; } |
Output
Enter the number of elements you want to input: 5
Enter 5 numbers: 1 2 3 4 5
You entered: 1 2 3 4 5
Time Complexity: O(n), where n is the number of elements you want to enter.
Space Complexity: O(n)
How to Take Multiple Input from User in C++?
In C++, we use cin when we want to take input from the user. We often also need to take more than one input at a time. In this article, we will learn how to take multiple inputs in C++.