![]() |
In C++, when taking user input, we may need to validate that it is a number and output an error if it is not. In this article, we will learn how to output an error when the input isn’t a number in C++. For Example, Input: Output Error When Input Isn’t a Number in C++The std::cin automatically deduces the type of data that is to be extracted from the input and puts it into the specified variable. We can use the (!) NOT operator with cin which is overloaded to check the state of the cin. The state of std::cin is set to bad when the input data type does not match the variable type. We can use this property to check whether the given data is a number or not. ApproachTo output an error when the input entered by the user is not a number do the following:
C++ Program to Output Error When Input isn’t NumberThe below example demonstrates how we can check and output an error when the input isn’t a number in C++. C++
Output: Please enter a number: g Time Complexity: O(1) |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |