Saturday, May 22, 2010

C++ Validation, input does not equal a character?

How do I validate that an input is not a character?


For example:





int money


cout %26lt;%26lt; "How many dollars do you have to spend (-1 to exit)? $";


cin %26gt;%26gt; money;





int "money" can be -1 and any other positive integer, but not characters and numbers less than -1. I'm thinking a while loop will do the trick?

C++ Validation, input does not equal a character?
First, don't allow input directly into a numeric data type but a string. Loop through the input character by character to determine if it's numeric-only or begins negative (-). Here's one attempt:





string str_money;





cout %26lt;%26lt; "How many dollars do you have to spend (-1 to exit)? $";


cin %26gt;%26gt; str_money;





int money_validation_flag = 1; // assume it's valid input until proven otherwise


int money_length = str_money.length(); // determine the input length


if (money_length == 0) money_validation_flag = 0;


else if (money_length == 1 %26amp;%26amp; !isdigit(str_money[0])) money_validation_flag = 0;


else if (!isdigit(str_money[0]) %26amp;%26amp; str_money[0]!='-') money_validation_flag = 0;


else for (int i=1; i%26lt;money_length; i++) if (!isdigit(str_money[i])) money_validation_flag = 0;





if (!money_validation_flag) cout %26lt;%26lt; "Dollar input validation problem with " %26lt;%26lt; str_money;





This version only looks for a positive integer or a negative number, not specifically -1. You can add that functionality after you convert to int (with atoi?). Also, you could recode this as a switch statement based on the length and it might look a bit cleaner.


No comments:

Post a Comment