Re: String parsing program



On 3 Jul, 19:56, pereges <Brol...@xxxxxxxxx> wrote:

Hi I've a string input and I have to parse it in such a way that that
there can be only white space till a digit is reached and once a digit
is reached, there can be only digits or white space till the string
ends. Am I doing this correctly ?  :

your spec is wrong. This is ok according to your spec: " 123 1 1 1 1
1 1"

        gets(s);

there is no way to prevent gets() from overflowing s.
See the comp.lang.c FAQ.
Use fgets() (it's slightly different so read the documentation
carefully)

<snip code>

I want to actually convert a string to unsigned long. So this kind of
algorithm should be carried out prior to strtoul function to ensure
that some of the weakness from which the strtoul function suffers like
convertin 123aaaaa to 123 for eg or -123 to some unsigned value is
removed. This will also ensure that when you have a string like :

1234 78

1234 is not returned but an error message will be printed. Because a
string should only contain 1 number in my program.

how about this:

/* scan.c */

/* #define VERBOSE */

#include <assert.h>
#include <stdio.h>

typedef int (*ScanFun) (const char*);

int scan (const char* s)
{
char number[11];
char junk[2];
int n;

/* assume 32 bit long */
assert (sizeof (unsigned long) <= 9999999999);

number[0] = 0;
junk[0] = 0;

n = sscanf (s, " %10[0123456789]%1s", number, junk);

#ifdef VERBOSE
printf ("scanned %d values number(%s) junk(%s)\n", n, number,
junk);
#endif

return n == 1;
}

void test(void)
{
ScanFun scan_f = scan;

assert (scan_f (" 123 "));
assert (scan_f ("123"));
assert (scan_f (" 123"));
assert (scan_f ("123 "));
assert (scan_f (" 1234567890"));
assert (scan_f (" 1234567890 "));

assert (!scan_f (" 123 456 "));
assert (!scan_f (" 12345678900 "));
assert (!scan_f (" 12345678900"));
assert (!scan_f (" 1234567890 qwertuiop"));
assert (!scan_f ("123ABC"));
assert (!scan_f (" "));
assert (!scan_f (""));
}

int main (void)
{
test();
printf ("\nall tests passed\a\n\n");
return 0;
}

--
Nick Keighley

As far as the laws of mathematics refer to reality, they are not
certain; and as far as they are certain, they do not refer to reality.
-- Albert Einstein
.



Relevant Pages