Input validation
-
Hi, I need your help plz. I have written a very simple program which prompt a user to enter his name and age. I only want to add some validation so that the user cannot enter numbers when he is asked to enter the name and prevent the user from inputting characters when prompted for age. I am using cin.getline(). Is there any way that i can do that. Please help.Thanks
-
Hi, I need your help plz. I have written a very simple program which prompt a user to enter his name and age. I only want to add some validation so that the user cannot enter numbers when he is asked to enter the name and prevent the user from inputting characters when prompted for age. I am using cin.getline(). Is there any way that i can do that. Please help.Thanks
-
Hi, I need your help plz. I have written a very simple program which prompt a user to enter his name and age. I only want to add some validation so that the user cannot enter numbers when he is asked to enter the name and prevent the user from inputting characters when prompted for age. I am using cin.getline(). Is there any way that i can do that. Please help.Thanks
-
you can also consider using the isdigit, and isalpha routines found in ctype.h Of all things I've lost... I miss my mind the most -mjf
-
Hi Thanks for the replies. You know am very new to C++, can you people please set a small example for me to elaborate on. Thanks
okay... skipping the ctype.h and regular expressions libraries, i've typed out a quick, simple example that shows how to validate a users input. It allows you to use cin.getline() and shows how to convert ASCII to int. I didn't intend to write it to do your homework but its more than sufficient for you to figure how to apply the basics to get your assignment done, and you really shouldn't use as is for any decent professor will dock you points for not writing better code - like I said... just to give you some insight. Good Luck
#include <string.h> #include <iostream.h> #include <stdlib.h> bool ValidateNumericInput(char* psBuf); int main(int argc, char* argv[]) { char sBuf[255]; do { cout << "enter a number" << endl; cin.getline(sBuf, 255, '\n'); }while ( !ValidateNumericInput(sBuf)); // at this point, the data in sBuf (to the NULL char) is numeric but in ASCII int iConverted = atoi(sBuf); // this converts the ASCII to an int cout<< endl << endl << ++iConverted; return 0; } // both cout statements were include just to display the results bool ValidateNumericInput(char* psBuf) { for (unsigned int index = 0; index < strlen(psBuf); index++) { if( psBuf[index] < 0x30 || psBuf[index] > 0x3F ) { cout << "'" << psBuf << "' - is an invalid entry" << endl << endl; return false; } } cout << "input was all numbers" << endl; return true; }//end of ValidateNumericInput() // there are many ways to achieve your desired result but I thought this might // give you some ideas
Of all things I've lost... I miss my mind the most -mjf