Using return value of cin to take unknown number of inputs in C++


Sometimes we need variable number of inputs in our program. In this program we will see how to use cin to take variable number of inputs.

The simple solution is run a loop, and when one specific value is pressed, it stops. The another idea is using the cin >> input. This will return false when value is non-numeric.

Example

#include <iostream>
using namespace std;
main() {
   int input;
   int n = 0;
   cout << "Enter numbers. (To stop enter any character): ";
   while (cin >> input)
   n++;
   cout << "\nTotal number of inputs entered: " << n;
}

Output

Enter numbers. (To stop enter any character): 
5
6
7
2
6
5
j
Total number of inputs entered: 6

Updated on: 30-Jul-2019

962 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements