first time user of strtol

hi i have to use strtol to error check that my second parameter is between 0 and 1023. if not i must print out "R".

i have this from a lecturer of which he recomended i look at, but i don't quite understand what is going on. could someone please explain it to, so i can attempt to do this range check

1
2
3
4
5
6
7
   char *perror_chars ;
   char **pperror_chars = &perror_chars ;
   long int the_number = strtol(argv[1], pperror_chars, 0);
   if ( strlen( perror_chars) != 0)
     { printf("     strtol found parameter 1 not a valid long integer: %s.\n", argv[1]) ;
       printf("      invalid integer characters start at %s\n", perror_chars) ;
     }
RTFM, ¿what part you don't understand? (the example in the manual pages is better)
http://linux.die.net/man/3/strtol
Last edited on
ok i looked at the link, i i understand it better, and i think i'm close. hewre is what i have


1
2
3
4
5
6
7
8
9
10
string min=0;
string max=1023;

char *end;
errno = 0;
strtol(argv[2], &end, 10);
if (errno != 0 && *end == '\0')
{
cout<<"R"<<endl;
}


i think i need to equate my ranges min and max to this, but i don't know how to do that. can you please show me?

thanks MGM
1
2
3
4
5
6
7
8
9
10
string min=0; //I think you shouldn't use strings here.
string max=1023;

char *end;
errno = 0;
strtol(argv[2], &end, 10); //you are not catching the returned value (the converted number)
if (errno != 0 && *end == '\0')
{
  cout<<"R"<<endl;
}

if( between(min, number, max) ) (you need to code between)
sorry i still don't understand. can you please show me?
int min=0; // define numerics as 'int' instead of 'string'
int max=1023;

char *end = NULL;
errno = 0;
long int num = strtol(argv[2], &end, 10); // returned value saved in 'num' variable
if ( strlen(end) != 0) { // 'errno' was zero even with invalid digits so don't use 'errno'
cout<<"R"<<endl;
} else if ( !((num >= min) && (num <= max)) )
cout<<"R"<<endl;
}

errno is only used for underflow or overflow, but it should still be checked.

1
2
3
4
5
6
 char* p = NULL;
 long l = strtol("4294967295", &p, 10);
 if(0 != errno)
	 cerr << "erk!" << endl;
 else
	 cerr << l << endl;


erk!

(4294967295 can be stored in an unsigned int but not a signed int)
Last edited on
Topic archived. No new replies allowed.