Re: Newbie: bug in argument casting to digit
From: Al Bowers (xabowers_at_rapidsys.com)
Date: 08/16/04
- Previous message: David Hopwood: "Re: POSIX and 8-bit bytes"
- In reply to: Jobs'R'Us: "Newbie: bug in argument casting to digit"
- Next in thread: Jobs'R'Us: "Re: Newbie: bug in argument casting to digit"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 16 Aug 2004 15:04:15 -0400
Jobs'R'Us wrote:
> Hello,
>
> I have a bug in a simple validation for an argument that must be an
> int from 1 to 99.
>
> If in the command prompt I enter the following, the program behaves
> perfectly:
> programname filename.txt doghouse 5
>
> If in the command prompt I enter the following, the program still
> behaves perfectly, it explains that the digit ("5all") is incorrect:
> programname filename.txt doghouse 5all
>
> The bug is, if I enter the following, the program incorrectly accepts
> "5a" and interprets it exactly like like "5":
> programname filename.txt doghouse 5a
>
> Someone kindly point out what I'm doing wrong?
>
> else if(strlen(argv[3]) > 2)
You are only checking the length of the string. You also
need to test to make sure the characters of the string are
digits.
Try:
else if(strlen(argv[3]) > 2 || !isdigit((unsigned char)argv[3][0] ||
!isdigit((unsigned char)argv[3][1])
> }
> {
> printf("Sorry, the number is wrong, must be a digit from 1 to
> 99...\n\n");
> printf("Usage: blah blah blah\n\n");
> return 3;
> }
> /* Program continues... */
>
You also have the option of using of of the strto* functions
provided by the Standard. With this program, you
might use function strtoul to validate that the string is valid.
Example of using strtoul is function ValidUINT defined below.
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
int ValidUINT(const char *src, unsigned *result)
{
char *s;
unsigned long tmp;
errno = 0;
tmp = strtoul(src,&s,10);
if(s == src || errno == ERANGE || *s != '\0' ||
tmp > UINT_MAX) return 0;
if(result) *result = tmp;
return 1;
}
You can use this function as follows;
change seracheddigit to
unsigned searcheddigit;
else if(!ValidUINT(argv[3],&searchddigit) || searcheddigit > 99)
/* Not valid or greater than 99 */
else /* Use searcheddigit. It is in range */
-- Al Bowers Tampa, Fl USA mailto: xabowers@myrapidsys.com (remove the x to send email) http://www.geocities.com/abowers822/
- Previous message: David Hopwood: "Re: POSIX and 8-bit bytes"
- In reply to: Jobs'R'Us: "Newbie: bug in argument casting to digit"
- Next in thread: Jobs'R'Us: "Re: Newbie: bug in argument casting to digit"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|