Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help with Numerical validation and vice versa

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi, I need help huys.

I want C++ to accept only numerical values from the user as input.
Other than that I want it to reject.

Example of how I would like it to work.

>Enter number: //User would enter number,anything else reject.

And another thing, I would love to know how to get C++
to accept oly charactors and reject numerical values too.

thanks in advance...
 
Pedros,

There is no easy quick and ready made way to do this. (nothing like if (input!= int) {} :( ). So you should receive the user input in a string. cin>>str. And then you may use functions like atoi(), or atol() to verify that the user entered a number. {one cute method would be...}

// say the user input is in strInput. then

first convert the string to an integer using atoi() function. If the user did enter an integer the function works fine, else it produces a wrong result. Now you convert this resulting integer back to string using itoa() function. This time the integer is converted to a string. Compare this string to the original strInput. If they are both equal then the user did enter an integer otherwise the user entered an invalid number i.e. not an integer.

Below is an example:

char strInput[256]; // holds the user input
char str1[256];
int number;

while (1)
{
cout<<&quot;Enter an integer: &quot;;
cin>>strInput;
number = atoi(strInput);
itoa(number, str1, 10);

// now compare str1 and strInput

if (strcmp(st1,strInput))
break; // the user entered an integer

}

/* other way would be to check strInput character y character to verify that the entered number is a
valid integer.
*/

cheers,
KAshif Manzoor When the going gets tough; the tough gets going; and the toughest of all sleeps zzzZZZ
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top