user62619
user62619

Reputation: 35

Simple way to validate command line arguments

How to check if argv (argument vector) contains a char, i.e.: A-Z

Would like to make sure that argv only contains unsigned intergers

For example:

if argv[1] contained "7abc7\0" - ERROR

if argv[1] contains "1234\0" - OK

Upvotes: 2

Views: 3947

Answers (4)

Mr Fooz
Mr Fooz

Reputation: 111866

 bool isuint(char const *c) {
   while (*c) {
     if (!isdigit(*c++)) return false;
   }
   return true;
 }

 ...
 if (isuint(argv[1])) ...

Additional error checking could be done for a NULL c pointer and an empty string, as desired.

update: (added the missing c++)

Upvotes: 5

hhafez
hhafez

Reputation: 39750

A much more flexible approach (ie: probably more than what you are asking for in your question) but is still very easy to use is using getopts which is part libc

Upvotes: 0

jpalecek
jpalecek

Reputation: 47762

How about this:

const std::string numbers="0123456789";

for(int i=1; i<argc; i++) {
  if(std::string(argv[i]).find_first_not_of(numbers)!=std::string::npos)
    // error, act accordingly
    ;
}

Upvotes: 1

Adam Davis
Adam Davis

Reputation: 93565

http://www.dreamincode.net/code/snippet591.htm

#include <iostream>
#include <limits>

using namespace std;

int main() {
  int number = 0;
  cout << "Enter an integer: ";
  cin >> number;
  cin.ignore(numeric_limits<int>::max(), '\n');

  if (!cin || cin.gcount() != 1)
    cout << "Not a numeric value.";
  else
    cout << "Your entered number: " << number;
  return 0;
}

Modified, of course, to operate on argv instead of cin.

This may not be exactly what you want though - run a few tests on it and check the output if you don't understand what it does.

-Adam

Upvotes: 0

Related Questions