### validating input question

howdy all, i need to validate user input. A string of numbers that allows "- +" signs, but not any other signs like "\$,%". i have it all working except for allowing one period. EI. 67.89 should be valid. I cant tell if i just messed up the punctuation statement or what. And i also do not know how to make it check for only one punctuation mark and return invalid for a second or third punctuation EI 76.54.32 would be invalid.

Any help would be appreciated!

punctuation validation is at line 53.

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364`` `````` #include #include #include using namespace std; bool isvalidInt(string); // function prototype (declaration) int main() { string value; double number; cout << "Enter an integer: "; getline(cin, value); if (!isvalidInt(value)) cout << "The number you entered is not a valid integer.\n\n"; else { number = atoi(value.c_str()); cout << "The integer you entered is " << number << endl; return 0; } } bool isvalidInt(string str) { int start = 0; int i; bool valid = true; // assume a valid bool sign = false; // assume no sign // check for an empty string if (str.length() == 0) valid = false; // check for a leading sign if ( valid && ( str.at(0) == '-'|| str.at(0) == '+' ) ) { sign = true; start = 1; // start checking for digits after the sign } // check that there is at least one character after the sign if (sign && str.length() == 1) valid = false; // now check the string, which we know has at least one non-sign char i = start; //check for punctuation mark only 1 if (ispunct(str)) i++; // we have checked i number of chars so far while(valid && i != str.length()) { if(!isdigit(str.at(i))) valid = false; //found a non-digit character i++; // move to next character } cout<<"chars checked: "<

Edit:

I tried moving it into the while loop, and that got rid of errors and it now runs but it does not seem to be checking for the punctuation at all.

 ``1234567891011121314`` `````` while(valid && i != str.length()) { if(!isdigit(str.at(i))) valid = false; //found a non-digit character i++; // move to next character //check for punctuation mark only 1 if (ispunct(str.at(i))) valid = false; i++; } cout<<"chars checked: "<
Last edited on
Topic archived. No new replies allowed.