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;
To stop enter any character Enter Your Input 1 2 3 s Total number of inputs entered: 3
This article is contributed by Aditya Rakhecha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- What does main() return in C and C++?
- return statement in C/C++ with Examples
- Return from void functions in C++
- Function overloading and return type
- How to return multiple values from a function in C or C++?
- C function argument and return values
- How to return a local array from a C/C++ function?
- Return values of printf() and scanf() in C/C++
- Increment a number without using ++ or +
- Program for n-th even number
- exp() function for complex number in C++
- pow() function for complex number in C++
- arg() function for Complex Number in C++
- cos() function for complex number in C++
- tan() function for complex number in C++
- Program for Sum of the digits of a given number
- Find the total Number of Digits in (N!)N
- polar() function for complex number in C++
- cosh() function for complex number in C++
- tanh() function for Complex Number in C++