[Courses] [C] Debugging (Re: help me find my C bug? (long))

Suzi Anvin suzi at anvin.org
Tue Jul 9 22:28:50 EST 2002


Hold on... pointers are chapters away yet!  :)  this is like my 3rd or 
4th day at this!  So far, all the programs I've been playing with are 
one-function programs and I've yet to have explained to me (by the book) 
the difference between global and local variables...  doing it the 
book's way for now, sand I'm really hoping they eventually explain WHY 
all the examples declare all the variables globally so far.  :)  Thanks 
for the input.  hehehe  I'm not quite ready to hack on gnome yet, 
though, I don't think.
			-Suzi

Christopher James Lahey wrote:

> The other however here is that I wouldn't use sscanf in the first place,
> but instead parse the string by hand using pointers.  This is probably
> something of a bias for me.  I don't trust any of the scanfs.  I would
> do something like:
> 
>     dollars = 0;
>     pointer = line;
>     while (isdigit(*pointer)) {
>       dollars *= 10;
>       dollars += *pointer - '0';
>       pointer ++;
>     }
>     if (*pointer == '.') {
>       pointer ++;
>     }
>     total = 0;
>     cent_digit = 0;
>     while (isdigit (*pointer)) {
>       cent_digit ++;
>       total *= 10;
>       total += *pointer - '0';
>       pointer ++;
>     }
>     if (cent_digit > 2) {
>       fprintf (stderr, "Not a proper dollar amount.\n");
>       continue;
>     }
>     if (*pointer != 0 && *pointer != '\n') {
>       fprintf (stderr, "Not a proper dollar amount.\n");
>       continue;
>     }
> 
> And then go on from there.  It's a bit longer, and doesn't do much
> extra, but it's much more explicit about what it does and doesn't do and
> isn't as forgiving if the user types an invalid input.
> 
> I like writing parsing code like this though.
> 
> Oh, one last thing.  As a matter of style and maintainability, I would
> put all of those variables inside of the main function since they don't
> need to be global.
> 
> Good luck with it,
>   Chris





More information about the Courses mailing list