1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include <iostream>
#include <sstream>
// if cstr contains the representation of an integer in [min_value,max_value]
// assign that integer to value and return true
// otherwise leave value unchanged and return false
bool to_int( const char* cstr, int& value, int min_value, int max_value )
{
std::istringstream stm(cstr) ;
int temp ;
if( stm >> temp && stm.eof() && temp >= min_value && temp <= max_value )
{
value = temp ;
return true ;
}
else return false ;
}
int main( int argc, char* argv[] )
{
enum { ARG1_MIN = -255, ARG1_MAX = 255,
ARG2_MIN = 1, ARG2_MAX = 65536, ARG2_DEFAULT = 1 } ;
if( argc < 2 ) { /* error */ }
else
{
int first ;
if( !to_int( argv[1], first, ARG1_MIN, ARG1_MAX ) ) { /* error */ }
int second = ARG2_DEFAULT ;
if( argc == 3 )
if( !to_int( argv[2], second, ARG2_MIN, ARG2_MAX ) ) { /* error */ }
// use first, second
}
}
|