How to Read Multiple Numbers from a Single Line of Input in C++?
Last Updated :
14 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > numbers;
int num;
cout << "Enter numbers separated by spaces: " ;
while (cin >> num) {
numbers.push_back(num);
}
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)
Share your thoughts in the comments
Please Login to comment...