The code for integer validation is :
int getNumber()
{
long Value;
bool correctInput = false;
while(!correctInput)
{
char *endPtr;
string Str;
Value = 0;
cout << "\n";
cin.sync();
cout << " Enter an integer : ";
getline(cin, Str, '\n');
cout << "\n";
errno = 0;
Value = strtol(Str.c_str(), &endPtr, 10);
// check if there is any overflow or underflow
if ((errno == ERANGE && (Value == LONG_MAX || Value == LONG_MIN)) || (errno != 0 && Value == 0))
{
cerr << " Numerical result out of range." << endl;
correctInput = false;
}
// check wheather input string containg any character
else if (endPtr == Str || *endPtr != '\0')
{
cerr << " Invalid input." << endl;
correctInput = false;
}
// otherwise correct input
else
{
correctInput = true;
}
}
return Value;
}
Its output is fine. Similarly I try to write the code for floating point number validation :
int getNumber()
{
double Value;
bool correctInput = false;
while(!correctInput)
{
char *endPtr;
string Str;
Value = 0;
cout << "\n";
cin.sync();
cout << " Enter a Number : ";
getline(cin, Str, '\n');
cout << "\n";
errno = 0;
Value = strtod(Str.c_str(), &endPtr);
// check if there is any overflow or underflow
if ((errno == ERANGE && (Value == HUGE_VALF || Value == HUGE_VALL)) || (errno != 0 && Value == 0))
{
cerr << " Numerical result out of range." << endl;
correctInput = false;
}
// check wheather input string containg any character
else if (endPtr == Str || *endPtr != '\0')
{
cerr << " Invalid input." << endl;
correctInput = false;
}
// otherwise correct input
else
{
correctInput = true;
}
}
return Value;
}
But the output for floating point number is something wrong, like:
tapas@My-Child:~/Programming/Input Validation$ ./"Float Input Validation.o"
Enter a Number : 123
You have entered : 123 <--Ok
tapas@My-Child:~/Programming/Input Validation$ ./"Float Input Validation.o"
Enter a Number : 12.3
You have entered : 12 <--Not ok (It will be 12.3)
tapas@My-Child:~/Programming/Input Validation$ ./"Float Input Validation.o"
Enter a Number : 12e3
You have entered : 12000 <--Ok
tapas@My-Child:~/Programming/Input Validation$ ./"Float Input Validation.o"
Enter a Number : 12e-3
You have entered : 0 <--Not ok (It will be 0.012)
tapas@My-Child:~/Programming/Input Validation$ ./"Float Input Validation.o"
Enter a Number : 12e-1
You have entered : 1 <--Not ok (It will be 1.2)
Another problem in the output is that if I press enter without giving any input it displays Invalid input. This problem can be solved using cin >> Str; instead of getline(cin, Str, '\n'); but if I use cin >> Str and give input 12 2 then it displays 12 because cin ignores whitespace, but 12 2 is an invalid input, because there can not be any space between numbers.
Is there any mistake in my code? Please help.
For both cases main function is:
int main()
{
cout << " You have entered : " << getNumber() << endl << endl;
return 0;
}
This post has been edited by Tapas Bose: 03 March 2010 - 01:03 AM

New Topic/Question
Reply




MultiQuote





|