Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 23 Jun, 2022
Improve Article
Save Article

Consider a problem where we need to take an unknown number of integer inputs. 

A typical solution is to run a loop and stop when a user enters a particular value. How to do it if we are not allowed to use if-else, switch-case, and conditional statements?

The idea is to use the fact that ‘cin >> input’ is false if the non-numeric value is given. Note that the above approach holds true only when the input value’s data type is int (integer). 

Important Point: cin is an object of std::istream. In C++11 and later, std::istream has a conversion function explicit bool() const;, meaning that there is a valid conversion from std::istream to bool, but only where explicitly requested. An if or while counts as explicitly requesting conversion to bool. [Source StackOVerflow

Before C++ 11, std::istream had a conversion to operator void*() const;

C++




// C++ program to take unknown number
// of integers from user.
#include <iostream>
using namespace std;
int main()
{
    int input;
    int count = 0;
    cout << "To stop enter anything except integer";
    cout << "\nEnter Your Input::";
 
    // cin returns false when anything
    // is entered except integer
    while (cin >> input)
        count++;
     
    cout << "\nTotal number of inputs entered: "
         << count;
    return 0;
}
 
//This code is updated by Susobhan Akhuli

Output: 

To stop enter any character
Enter Your Input 1 2 3 s
Total number of inputs entered: 3

Time Complexity: O(count)
Auxiliary Space: O(1)

This article is contributed by Aditya Rakhecha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!