简体   繁体   中英

Command Line Arguments error checking, see if whole argument is an integer

int main(int argc, char *argv[])
{
  if(!isdigit(*argv[1]))
  {
    cerr << "Error msg" << endl;
    return 1;
  }
}

Hey guys, for part of my program, I have to check if the first argument (argv[1]) is an integer or not. If the given argument is not an integer, it prints out the error msg and exits the program, if not it continues executing. I've gotten my program to correctly find an error when the argument is a regular string, such as dzd or xy, but it fails to find an error when the given argument starts with a number, such as 1dzd or 32st. I was wondering if any of you guys could help me figure out how to change or add to the given code to make it so that it can correctly find errors for arguments such as 1dzd or 32st?

Thanks!

One way is to use an istringstream to check if the conversion to an int is possible:

int val;
std::istringstream iss(argv[1]);

if(!(iss >> val)) {
    cerr << "Error msg" << endl;
    return 1;
}

You are only checking if the first char is a digit. The following code will check if the entire argument is a number. That or you can just us the standard function strtol.

char *ch = argv[1];

while(*(ch++) != 0) {
    if(!isdigit(*argv[1]))
    {
        cerr << "Error msg" << endl;
        return 1;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM