Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // What is likely a far too complex/cludgy/etc. attempt at basic input validation? :s
- #include <cctype> // for isalpha() - isdigit() - and friends
- #include <cstdlib> // for atoi()
- #include <cstring> // for strlen()
- #include <iomanip> // for setw()
- #include <iostream>
- using namespace std;
- // Input validation function prototypes
- bool isWholeNum (char[]);
- bool isAlphaStr (char[]);
- int main()
- {
- char a;
- char firstName[16], lastName[16], age[4];
- do
- {
- cout << "\nEnter your first name: ";
- cin >> setw(16) >> firstName;
- cin.ignore(1000, '\n');
- // Catch errors and loop the get input stage until proper input has been entered
- while (!isAlphaStr(firstName) || !(strlen(firstName) > 1))
- {
- cout << "\nError: invalid input, please try again.\n";
- cout << " Hint: only use alphabetical characters.\n";
- cout << "\nEnter your first name: ";
- cin >> setw(16) >> firstName;
- cin.ignore(1000, '\n');
- }
- // Once we've gotten a proper response to the first question, continue
- cout << "Enter your last name: ";
- cin >> setw(16) >> lastName;
- cin.ignore(1000, '\n');
- // Catch errors and loop the get input stage until proper input has been entered
- while (!isAlphaStr(lastName) || !(strlen(lastName) > 1))
- {
- cout << "\nError: invalid input, please try again.\n";
- cout << " Hint: only use alphabetical characters.\n";
- cout << "\nEnter your last name: ";
- cin >> setw(16) >> lastName;
- cin.ignore(1000, '\n');
- }
- // Once we've gotten a proper response to the second question, continue
- cout << "Enter your age: ";
- cin >> setw(4) >> age;
- cin.ignore(1000, '\n');
- // Catch errors and loop the get input stage until proper input has been entered
- while (!isWholeNum(age) || !(atoi(age) > 0))
- {
- cout << "\nError: invalid input, please try again.\n";
- cout << " Hint: only use positive, whole numbers.\n";
- cout << "\nEnter your age: ";
- cin >> setw(4) >> age;
- cin.ignore(1000, '\n');
- }
- // Once we've gotten a proper response to the last question, continue
- cout << "\nGreetings, " << firstName << " " << lastName << " (" << age << ")\n";
- cout << "\nRun the program again? y/n? ";
- cin.get(a);
- cin.ignore();
- }
- while (tolower(a) == 'y');
- return 0;
- }
- // Determines if user input is a positive whole number
- bool isWholeNum (char cArray[])
- {
- unsigned short index = 0;
- while(cArray[index] != '\0')
- {
- if (!isdigit(cArray[index]))
- return false;
- ++index;
- }
- return true;
- }
- // Determines if user input is a string of nothing but alphabetical characters
- bool isAlphaStr (char cArray[])
- {
- unsigned short index = 0;
- while(cArray[index] != '\0')
- {
- if (!isalpha(cArray[index]))
- return false;
- ++index;
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment