Search code examples
c++functionargvargc

Checking if argv[i] is a valid integer, passing arguments in main


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?


Solution

  • 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.