How to Read Multiple Numbers from a Single Line of Input in C++?
In C++, when working with user inputs we often need to take input of multiple numbers from a user in a single line. In this article, we will learn how to read multiple numbers from a single line of input in C++.
Example
Input: 1 7 0 4 6 8 Output: Entered Number: 1, 7, 0, 4, 6, 8
Take Multiple Numbers as Input in One Line in C++
To read multiple numbers from a user in one line, we can use the std::cin object as it by default takes the input separated by a whitespace as a separate input. So, if the numbers are separated by a whitespace, we can take them as input in multiple number variables.
C++ Program to Read Multiple Numbers from Single Line of Input
The below example demonstrates the use of cin to read the whole line and take the input as separate variables.
C++
// C++ program to read multiple numbers in a single line of // input #include <iostream> #include <vector> using namespace std; int main() { vector< int > numbers; int num; // Prompt the user to enter numbers separated by spaces cout << "Enter numbers separated by spaces: " ; // Input numbers until the user enters something other // than an integer while (cin >> num) { // Add the entered number to the vector numbers.push_back(num); } // Output the entered numbers cout << "You entered: " ; for ( int i : numbers) { cout << i << " " ; } cout << endl; return 0; } |
Output
Enter multiple numbers separated by spaces: 1 2 3 4 5
Processed numbers: 1 2 3 4 5
Time Complexity: O(n)
Space Complexity: O(n)