Tutorialspoint.dev

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

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 statement.

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

Important Point : cin is an object if 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 a conversion to bool. [Source StackOVerflow]
Before C++ 11, std::istream had a conversion to operator void*() const;

// CPP 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 any character";
    cout << " Enter Your Input::";
  
    // cin returns false when a character
    // is entered
    while (cin >> input) 
        count++; 
      
    cout << " Total number of inputs entered: " 
         << count;
    return 0;
}

Output:

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

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

1 Comments

load comments

Subscribe to Our Newsletter