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

user1940516 picture user1940516 · Oct 15, 2013 · Viewed 8.5k times · Source

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?

Answer

Yu Hao picture Yu Hao · Oct 15, 2013

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