Question

I'm trying to make sure all arguments passed to main are valid integers, and if not, I'll 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 there's an invalid integer, so if I enter total 1 2 3zy it will print an error message. My code is as follows.

#include <iostream>
#include<stdlib.h>
using namespace std;

bool legal_int(char *str);

int main(int argc, char *argv[])
{
 //int total = 0;
 for(int i = 1; i < argc; i++)
 {
  if( (legal_int(argv[i]) == true) )
  {
   cout << "Good to go" << endl;
  }
  else
  {
   cerr << "Error: illegal integer." << endl;
   return 1;
  }
 }

  // int value = atoi(argv[i]);
  //cout << value << endl;
}

bool legal_int(char *str)
{
 while(str != 0) // need to
 if( (isdigit(str)) )// do something here
 {
  return true;
 }
 else
 {
  return false;
 }
}

What I need to know is how can I index through all the characters in the string and make sure they are digits with the legal_int function?

Was it helpful?

Solution 3

bool legal_int(char *str)
{
 while(str != 0) // need to
 if( (isdigit(str)) )// do something here
 {
  return true;
 }
 else
 {
  return false;
 }
}

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. return true; That should not be there. You don't want to return just because you found a single digit.

OTHER TIPS

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;
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top