Code will check whether the number entered is integer or not. ignore
extracts characters from the input sequence and discards them. The extraction ends when max characters have been extracted and discarded or when the character delim(\n) is found, whichever comes first.
In the latter case, the delim character itself is also extracted. numeric_limits<int>::max()
- Returns the maximum finite value for integer. gcount
- returns the number of characters extracted by the last unformatted input operation performed on the object.
Input Validation in C++
#include <iostream>
#include <limits>
using namespace std;
int main() {
int number = 0;
cout << "Enter an integer: ";
cin >> number;
cin.ignore(numeric_limits<int>::max(), '\n');
if (!cin || cin.gcount() != 1)
cout << "Not a numeric value.";
else
cout << "Your entered number: " << number;
return 0;
}
munyu 0 Newbie Poster
JLChafardet 0 Newbie Poster
JLChafardet 0 Newbie Poster
mrnutty 761 Senior Poster
VikyTushar 0 Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.