I wrote the following code to check whether the input(answer3) is a number or string, if it is not a number it should return "Enter Numbers Only" but it returns the same even for numbers. Please suggest me a solution.
#include <iostream>
#include <string>
#include <typeinfo>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
using namespace std;
int main ()
{
string ques1= "Client's Name :";
string ques2 = "Client's Address :";
string ques3 = "Mobile Number :";
char answer1 [80];
string answer2;
int answer3;
cout<<ques1<<endl;
cin>>answer1;
cout<<ques2<<endl;
cin>>answer2;
cout<<ques3<<endl;
cin>>answer3;
if (isdigit(answer3))
{
cout<<"Correct"<<endl;
}
else
{
cout<<"Enter Numbers Only"<<endl;
}
system("pause>null");
return 0;
}
isdigittakes a single character as anint, interprets it as an ASCII character, and returns nonzero if it's a digit character ('0' through '9', ASCII 48 through 57) or zero if it's not. It has no way to tell you if you read an integer intoanswer3.cin >> someIntVariablediscards leading whitespace, reads an optional sign (-or+) followed by a sequence of digits, stopping at the first non-digit character. So if someone enters something that can't be interpreted, it sets the variable to 0. Which is whyisdigitlater fails.isdigiton anintegerunless you know precisely what it means for an integer to be a digit.