views:

351

answers:

4

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
A: 

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 Davis
+5  A: 
 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++)

Mr Fooz
Nice one, i knew there must have been a way.
Wouldn't that need a c++? while (*c) { if (!isdigit(*c++)) ... } (no pun intended!)
David Zaslavsky
it would for sure
hhafez
Added. Thanks for the catch.
Mr Fooz
+1  A: 

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
    ;
}
jpalecek
A: 

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

hhafez
@hharez: But is not standard C++?
Aaron
On what platform are you working on? If you have the gnu libc then it will work.
hhafez
Windows (Win32) - I tend to use it when programming in C (linux)
Aaron
I don't beleive the gnu libc is availble for Win32 is it? If not then there it is not available unless there is an equivelant, but for linux c or c++ development it is there for sure
hhafez
No its not. But there are alternatives - see: http://www.codeguru.com/forum/showthread.php?t=393293 ( cool! :) )
Aaron
Ummm...I don't see any way to specify that a parameter must meet certain characteristics (all-numeric, for instance). I don't think getopt actually solves the problem at hand!
Michael Kohne