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.
#include <iostream>
#include <string>
#include <cctype>
usingnamespace 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: "<<i<<"\n\n";
return valid;
}
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
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: "<<i<<"\n\n";
return valid;
}