im trying to make sure all arguments passed to main are valid integers, and if not, ill print an error. For example, if i have an executable named total, i would enter total 1 2 3 4. I want to print an error if theres an invalid integer, so if i enter total 1 2 3zy it will print an error message. My code is as follows.

  1 #include <iostream>
  2 #include<stdlib.h>
  3 using namespace std;
  4 
  5 bool legal_int(char *str);
  6 
  7 int main(int argc, char *argv[])
  8 {
  9  //int total = 0;
 10  for(int i = 1; i < argc; i++)
 11  {
 12   if( (legal_int(argv[i]) == true) )
 13   {
 14    cout << "Good to go" << endl;
 15   }
 16   else
 17   {
 18    cerr << "Error: illegal integer." << endl;
 19    return 1;
 20   }
 21  }
 22 
 23   // int value = atoi(argv[i]);
 24   //cout << value << endl;
 25 }
 26 
 27 bool legal_int(char *str)
 28 {
 29  while(str != 0) // need to
 30  if( (isdigit(str)) )// do something here
 31  {
 32   return true;
 33  }
 34  else
 35  {
 36   return false;
 37  }
 38 }

What i need to know is how can I index through all characters in the string and make sure they are digits with the legal_int function. If someone could point me in the right direction thatd be great! If anymore clarification is needed, just ask.

3 Answers

0
David Schwartz On Best Solutions
27 bool legal_int(char *str)
28 {
29  while(str != 0) // need to
30  if( (isdigit(str)) )// do something here
31  {
32   return true;
33  }
34  else
35  {
36   return false;
37  }
38 }

You have three mistakes:

  1. while (str != 0) should be while (*str != 0). You want to continue until you encounter a zero in the string, not until the string itself goes away.

  2. if( (isdigit(str)) ) should be if( (isdigit(*str++)) ). You want to look at what str points to and see if that's a digit, and you need to point to the next digit.

  3. 32 return true; That should not be there. You don't want to return just because you found a single digit.

1
D.Shawley On

What about:

bool legal_int(char *str) {
    while (*str)
        if (!isdigit(*str++))
            return false;
    return true;
}

It is not the best function but it should serve the purpose. The isdigit function needs a character to look at so pass in *str. The other key point is that you need to advance the pointer inside of the loop.

3
Yu Hao On

When comparing every character, the logic should be if it's not legal, return false, otherwise continue:

bool legal_int(char *str)
{
    while (str != 0)
    {
        if (!isdigit(*str)) 
        {
           return false;
        }
        str++;
    }
    return true;
}