I have this code to test whether or not the user is inputting bad data.
static bool intOK(string s)
{
bool OK = true;
int p1, p2;
int f;
//finds 1st character after white space
for(p1 = 0; p1<s.length()&&isspace(s[p1]); p1++);
cout << "p1 = " << p1 << " ";
//white space entered
if (p1 == s.length()) //entered only white space
return false;
//finds p2, where trailing white space might begin
for(p2=s.length()-1; isspace(s[p2]); p2--);
cout << "p2 = " << p2 << " ";
//in case of a hyphen being p1, then continue
if (s[p1]== '-')
if (s.length() > p1+1 && isdigit(s[p1+1]))
p1++;
else
return false;//because there was no digit to the right of the hyphen
for(f=p1; f<=p2; f++)
if (!isdigit(s[f])) return false;
//s="Test";
return true;
and below i have a function that will insert commas into the right place of the integer. that is if the user typed in an acceptable integer.
static string commaInt(long num)
{
//(5 points) Replace this stub code with code that implements the
//logic suggested by the description of the commaInt function above.
char temp[80]; //make extra big to be safe
int i, x;
however this final function isn't working at all, i think it has to do with my for loop's logic. b/c i can compile the code fine, its just there isnt any commas anywhere in the output.
If you want to remove any leading whitespace. Just use the string.find_first_not_of() function. Then you can use string.substr() to trim the string down to size. Then you can use string.find_last_not_of() and test it to see if there are trailing whitespaces.
itoa is also not advised, as it'll return 0 on failure. 0 Can be a perfectly valid number for alot of applications.