473,473 Members | 1,477 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

String parsing program

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 ? :

Code:

#include <stdio.h>
#include <string.h>

int main(void)
{
char s[50];
int i = 0;

gets(s);

while (isspace(s[i]))
i++;
while (isdigit(s[i]))
i++;
while (isspace(s[i]))
i++;
if (s[i] != '\0')
printf("\nIncorrect string\n");

return (0);
}

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.
Jul 3 '08 #1
28 2156
pereges 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 ? :

Code:

#include <stdio.h>
#include <string.h>

int main(void)
{
char s[50];
int i = 0;

gets(s);

while (isspace(s[i]))
i++;
while (isdigit(s[i]))
i++;
while (isspace(s[i]))
i++;
if (s[i] != '\0')
printf("\nIncorrect string\n");

return (0);
}
A string completely of whitespace will pass your test.

<snip>

Jul 3 '08 #2
On Jul 4, 12:21 am, santosh <santosh....@gmail.comwrote:
A string completely of whitespace will pass your test.
It will be caught by strtoul, I think. But anyway one can extend it
for that case as well:

char s[50];
int i = 0;

gets(s);

while (isspace(s[i]))
i++;
if (s[i] == '\0')
printf("Invalid string\n");
Jul 3 '08 #3
pereges wrote:
On Jul 4, 12:21 am, santosh <santosh....@gmail.comwrote:
>A string completely of whitespace will pass your test.

It will be caught by strtoul, I think. But anyway one can extend it
for that case as well:

char s[50];
int i = 0;

gets(s);

while (isspace(s[i]))
i++;
if (s[i] == '\0')
printf("Invalid string\n");
Also isspace will return true for whitespace characters like vertical
tab, newline, carriage return and form feed. If you only want to allow
space and horizontal tab in input then consider isblank.

Jul 3 '08 #4
On Jul 4, 12:31 am, santosh <santosh....@gmail.comwrote:
Also isspace will return true for whitespace characters like vertical
tab, newline, carriage return and form feed. If you only want to allow
space and horizontal tab in input then consider isblank.
Thanks for the suggestion but from what I see, it works with isspace
as well. Btw here's my program for parsing doubles/floats (not in
exponential form) :

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
char s[50];
int i;

gets(s);

i = 0;

while(isblank(s[i]))
{
i++;
}

if (s[i] == '+' || s[i] == '-')
{
i++;
}

if (isdigit(s[i]))
{
while (isdigit(s[i]))
{
i++;
}

if (s[i] == '.')
{
i++;

if (isdigit(s[i]))
{
while (isdigit(s[i]))
{
i++;
}
while (isblank(s[i]))
{
i++;
}
if (s[i] != '\0')
{
printf("Invalid String\n");
return (EXIT_FAILURE);
}
}
else
{
printf("Invalid String\n");
return (EXIT_FAILURE);
}
}
else
{
printf("Invalid string\n");
return (EXIT_FAILURE);
}
}
else
{
printf("Invalid string\n");
return (EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
Jul 3 '08 #5
pereges wrote:
On Jul 4, 12:31 am, santosh <santosh....@gmail.comwrote:
>Also isspace will return true for whitespace characters like vertical
tab, newline, carriage return and form feed. If you only want to
allow space and horizontal tab in input then consider isblank.

Thanks for the suggestion but from what I see, it works with isspace
as well. Btw here's my program for parsing doubles/floats (not in
exponential form) :
<snip code>

Your code exhibits undefined behaviour because you have failed to
include ctype.h where the declarations for the is* functions are.
Didn't your compiler warn you about missing declarations? If not, then
set it to the highest possible ISO C conformance and diagnostic levels.

Jul 3 '08 #6
On Jul 4, 1:24 am, santosh <santosh....@gmail.comwrote:
Your code exhibits undefined behaviour because you have failed to
include ctype.h where the declarations for the is* functions are.
Didn't your compiler warn you about missing declarations? If not, then
set it to the highest possible ISO C conformance and diagnostic levels.
I'm using digital mars compiler. Yes, I included the ctype.h now and
it still works (for some eg. I took).
Jul 3 '08 #7
pereges wrote:
On Jul 4, 1:24 am, santosh <santosh....@gmail.comwrote:
>Your code exhibits undefined behaviour because you have failed to
include ctype.h where the declarations for the is* functions are.
Didn't your compiler warn you about missing declarations? If not,
then set it to the highest possible ISO C conformance and diagnostic
levels.

I'm using digital mars compiler. Yes, I included the ctype.h now and
it still works (for some eg. I took).
One of the first things to do after installing a compiler is to read
it's documentation and find out the switches to supply for enabling
strictest conformance to ISO C and emit maximum possible diagnostics.
It's of greatest help when attempting to write robust, standard C
programs.

For Digital Mars you would probably want to use the '-A95' or '-A99'
option. All warnings are apparently enabled by default. Also consider
the '-r' option, which would have warned you about not including
ctype.h in above code. You can also use the '-p' switch to turn off
the "autoprototyping" feature, which can be dangerous for newbies.

Jul 3 '08 #8
pereges <Br*****@gmail.comwrites:
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.
<snip>
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.
I am not a fan of pre-scanning. It seems like duplicating the effort
already put in by the library author! I think you have been
(slightly) led-astray -- in part because people have just answered the
questions you've asked, and in part because I am ignorant! (See
below...)
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.
The simplest way to scan for a number whilst reporting bad input is to
use the signed strtol function. You check that errno has not been set
to ERANGE and that the end-pointer is not the string you passed in.
If you like, you can now check that nothing but white space is left in
the string. Finally, you confirm the input is the range your program
expects. The signed version lets you detect input like -123. The down
side is that you loose half the range of possible inputs. If that
matters, you can (probably) go up to strtoll.

[Aside. I feel I must "come clean". Until today I did not know that
strtoul accepted "-123" as a valid number[1]. Of course it does the
right thing with it but you can't tell, from the result alone, that
the input was not 4294967173[2]. If I'd been more clued up on that at
the start, I'd have advised the use of strtol right from the get-go.]

[1] Well, I might have known. It seems a strangely familiar
discovery, but it was not up there at the front on my brain where it
was needed to give the best advice. The OP is validating input and,
for most application end users, C's interpretation of (unsigned
long)-123 is just baffling. strtoul is not the right tool.

[2] YMMV

--
Ben.
Jul 3 '08 #9
pereges <Br*****@gmail.comwrites:
On Jul 4, 12:31 am, santosh <santosh....@gmail.comwrote:
>Also isspace will return true for whitespace characters like vertical
tab, newline, carriage return and form feed. If you only want to allow
space and horizontal tab in input then consider isblank.

Thanks for the suggestion but from what I see, it works with isspace
as well. Btw here's my program for parsing doubles/floats (not in
exponential form) :
STOP!

This way madness lies. If you need to enforce a simplified input
syntax then, OK, I see the point but otherwise strtod will do it all
for you. stroul has an oddity in that it accepts some strings that
might confuse your users, but I don't think strtod has any similar
problems. Of course, I am hardly an authority in the area now!

I think you are making work for yourself.

--
Ben.
Jul 3 '08 #10
On Jul 4, 2:14 am, Ben Bacarisse <ben.use...@bsb.me.ukwrote:
<snip>
The simplest way to scan for a number whilst reporting bad input is to
use the signed strtol function. You check that errno has not been set
to ERANGE and that the end-pointer is not the string you passed in.
If you like, you can now check that nothing but white space is left in
the string. Finally, you confirm the input is the range your program
expects. The signed version lets you detect input like -123. The down
side is that you loose half the range of possible inputs. If that
matters, you can (probably) go up to strtoll.
<snip>
My input is of following format :

45 5666 16000

^^ All of that is just a single string. I need to read the three
numbers into 3 different size_t variables. There can be white space
amongst them but no alphabets or any other characters. It is possible
check if *endp character is nothing but white space (This must be done
when errno != ERANGE and s != endp i.e. when one usually expects
correct output), but any character other than that means data is
erroneous. With unsigned long, you can check if the first non white
space character is a '-' or not. This should solve the problem of
negative numbers as well and prevent their conversion to some unsigned
value before hand.
Jul 3 '08 #11
santosh wrote:
Your code exhibits undefined behaviour because you have failed to
include ctype.h where the declarations for the is* functions are.
Not really. The default declarations will do for those. It's not good
practice, of course.


Brian


Jul 3 '08 #12
pereges <Br*****@gmail.comwrites:
On Jul 4, 2:14 am, Ben Bacarisse <ben.use...@bsb.me.ukwrote:
><snip>
The simplest way to scan for a number whilst reporting bad input is to
use the signed strtol function. You check that errno has not been set
to ERANGE and that the end-pointer is not the string you passed in.
If you like, you can now check that nothing but white space is left in
the string. Finally, you confirm the input is the range your program
expects. The signed version lets you detect input like -123. The down
side is that you loose half the range of possible inputs. If that
matters, you can (probably) go up to strtoll.
<snip>

My input is of following format :

45 5666 16000

^^ All of that is just a single string. I need to read the three
numbers into 3 different size_t variables. There can be white space
amongst them but no alphabets or any other characters. It is possible
check if *endp character is nothing but white space (This must be done
when errno != ERANGE and s != endp i.e. when one usually expects
correct output), but any character other than that means data is
erroneous. With unsigned long, you can check if the first non white
space character is a '-' or not. This should solve the problem of
negative numbers as well and prevent their conversion to some unsigned
value before hand.
Here is one way based on using the widest signed type for input. It
is not ideal, but then without very details specs, what could be? If
you need to accept input right up to SIZE_MAX and you have an
implementation where intmax_t can't hold that value, then you will
need to use strtoumax and check for the - manually, so to speak. That
would not be a big change to parse_size.

#include <stdio.h>
#include <stdbool.h>
#include <inttypes.h>
#include <stdint.h>
#include <errno.h>
#include <ctype.h>

size_t parse_size(const char *num, const char **endp, bool *error)
{
char *ep;
errno = 0;
intmax_t imax = strtoimax(num, &ep, 10);
if (errno == ERANGE || imax < 0 || imax SIZE_MAX) {
while (isspace(*num))
num++;
fprintf(stderr, "Input \"%.*s\" out of range.\n",
ep - num, num);
if (error)
*error = true;
}
else if (ep == num) {
/* Skip to the next space-delimited portion of the string. */
while (isspace(*ep))
ep++;
num = ep;
while (*ep != '\0' && !isspace(*ep))
ep++;
fprintf(stderr, "Input \"%.*s\" could not be converted.\n",
ep - num, num);
if (error)
*error = true;
}
if (endp)
*endp = ep;
return imax;
}

void parse_three_sizes(const char *input)
{
bool errors = false;
const char *ep;
size_t s1 = parse_size(input, &ep, &errors);
size_t s2 = parse_size(ep, &ep, &errors);
size_t s3 = parse_size(ep, &ep, &errors);

if (!errors) {
/* Check that everything parsed. */
const char *save_ep = ep;
while (isspace(*ep))
ep++;
if (*ep != '\0')
fprintf(stderr, "Superfluous input found: \"%s\"\n", save_ep);
printf("Got: %zu %zu %zu\n", s1, s2, s3);
}
}

int main(int argc, char **argv)
{
if (argc 1)
parse_three_sizes(argv[1]);
return 0;
}

--
Ben.
Jul 3 '08 #13
"Default User" <de***********@yahoo.comwrites:
santosh wrote:
>Your code exhibits undefined behaviour because you have failed to
include ctype.h where the declarations for the is* functions are.

Not really. The default declarations will do for those. It's not good
practice, of course.
That works only in C90. Even though there are few full C99 compilers,
it doesn't hurt to write good C90 code that's also valid C99 code.

And the is* and to* functions are very likely to be implemented as
macros, with better performance than the function calls. By not
including the header, you miss out on the macro definitions.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 4 '08 #14
Keith Thompson wrote:
"Default User" <de***********@yahoo.comwrites:
santosh wrote:
Your code exhibits undefined behaviour because you have failed to
include ctype.h where the declarations for the is* functions are.
Not really. The default declarations will do for those. It's not
good practice, of course.

That works only in C90. Even though there are few full C99 compilers,
it doesn't hurt to write good C90 code that's also valid C99 code.
So? In that case there's a required diagnostic for the missing
declaration.
And the is* and to* functions are very likely to be implemented as
macros, with better performance than the function calls. By not
including the header, you miss out on the macro definitions.
But not undefined behavior.


Brian
Jul 4 '08 #15
pereges 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 ? :

Code:

#include <stdio.h>
#include <string.h>

int main(void)
{
char s[50];
int i = 0;

gets(s);
Real bad example.
>
while (isspace(s[i]))
while ((unsigned char) s[i])
i++;
while (isdigit(s[i]))
i++;
This does not _require_ a digit to be present.
while (isspace(s[i]))
i++;
if (s[i] != '\0')
printf("\nIncorrect string\n");
return (0);
}

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
That is not a weakness but a strength.

x = strtoul(str, &endp, 0);

if (endp != str)
while (isspace((unsigned char) endp))
endp++;

if (endp != str && *endp == 0)
/* all good */;
for eg or -123 to some unsigned value is removed.
if (endp != str && *endp == 0 && strchr(str,'-') == 0)
/* all good */;

--
Peter
Jul 4 '08 #16
Default User wrote:
Keith Thompson wrote:
>"Default User" <de***********@yahoo.comwrites:
>>santosh wrote:
Your code exhibits undefined behaviour because you have failed to
include ctype.h where the declarations for the is* functions are.
Not really. The default declarations will do for those. It's not
good practice, of course.
That works only in C90. Even though there are few full C99 compilers,
it doesn't hurt to write good C90 code that's also valid C99 code.

So? In that case there's a required diagnostic for the missing
declaration.
>And the is* and to* functions are very likely to be implemented as
macros, with better performance than the function calls. By not
including the header, you miss out on the macro definitions.

But not undefined behavior.
The common subset of C90 and C99,
is like C90 with less allowable sloppy style.

It's a better way to write C90 code,
even if you don't intend it to be compiled as C99 code,

--
pete
Jul 4 '08 #17
"Default User" <de***********@yahoo.comwrites:
Keith Thompson wrote:
>"Default User" <de***********@yahoo.comwrites:
santosh wrote:
Your code exhibits undefined behaviour because you have failed to
include ctype.h where the declarations for the is* functions are.

Not really. The default declarations will do for those. It's not
good practice, of course.

That works only in C90. Even though there are few full C99 compilers,
it doesn't hurt to write good C90 code that's also valid C99 code.

So? In that case there's a required diagnostic for the missing
declaration.
>And the is* and to* functions are very likely to be implemented as
macros, with better performance than the function calls. By not
including the header, you miss out on the macro definitions.

But not undefined behavior.
You're right, there's no undefined behavior in either C90 or C99.

(Well, there's a constraint violation in C99; if the implementation
accepts the program in spite of that, after issuing the required
diagnostic, then the behavior is undefined. But that's stretching the
point.)

Failing to include <ctype.hwhen using the is* or to* functions is
still a bad idea, of course.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 4 '08 #18
pereges said:
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 ? :
No.

gets(s);
Until you have learned why you must never call this function, there is
little point trying to learn anything else about C. This is your next
step. Trying to jump over it is most unwise.

<snip>

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jul 4 '08 #19
pete wrote:
Default User wrote:
But not undefined behavior.
It's a better way to write C90 code,
even if you don't intend it to be compiled as C99 code,

What does this have to do with what I said?

Brian
Jul 4 '08 #20
Keith Thompson wrote:
"Default User" <de***********@yahoo.comwrites:
But not undefined behavior.

You're right, there's no undefined behavior in either C90 or C99.

(Well, there's a constraint violation in C99; if the implementation
accepts the program in spite of that, after issuing the required
diagnostic, then the behavior is undefined. But that's stretching the
point.)

Failing to include <ctype.hwhen using the is* or to* functions is
still a bad idea, of course.

Which is probably why I said, "It's not good practice, of course."

Brian
Jul 4 '08 #21
On 4 Jul, 04:20, Peter Nilsson <ai...@acay.com.auwrote:
pereges wrote:
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

That is not a weakness but a strength.
well not if that isn't what he wants...

--
Nick Keighley
Jul 4 '08 #22
On Thu, 3 Jul 2008 11:56:06 -0700 (PDT), pereges <Br*****@gmail.com>
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 ? :

Code:

#include <stdio.h>
#include <string.h>

int main(void)
{
char s[50];
int i = 0;

gets(s);
You have to be trolling to still use this.
>
while (isspace(s[i]))
i++;
while (isdigit(s[i]))
i++;
while (isspace(s[i]))
i++;
if (s[i] != '\0')
printf("\nIncorrect string\n");
If the input is "9 5", you will fail the string even though it meets
your verbal definition.
>
return (0);
}

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
You can call this a weakness if you like but strtoul will provide you
enough info to detect the situation with a lot less code than if you
do it yourself.
>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.
Except that a couple of messages down in this thread you state
explicitly that you want to accept this type of input.
Remove del for email
Jul 4 '08 #23
On Thu, 3 Jul 2008 13:14:31 -0700 (PDT), pereges <Br*****@gmail.com>
wrote:
>On Jul 4, 12:31 am, santosh <santosh....@gmail.comwrote:
>Also isspace will return true for whitespace characters like vertical
tab, newline, carriage return and form feed. If you only want to allow
space and horizontal tab in input then consider isblank.

Thanks for the suggestion but from what I see, it works with isspace
as well. Btw here's my program for parsing doubles/floats (not in
exponential form) :

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
char s[50];
int i;

gets(s);

i = 0;

while(isblank(s[i]))
{
i++;
}

if (s[i] == '+' || s[i] == '-')
{
i++;
}

if (isdigit(s[i]))
For some reason you have decided that ".5" is not valid input for a
double.
{
while (isdigit(s[i]))
{
i++;
}

if (s[i] == '.')
{
i++;

if (isdigit(s[i]))
{
while (isdigit(s[i]))
{
i++;
}
while (isblank(s[i]))
{
i++;
}
if (s[i] != '\0')
{
printf("Invalid String\n");
return (EXIT_FAILURE);
}
}
else
{
printf("Invalid String\n");
return (EXIT_FAILURE);
}
}
else
{
printf("Invalid string\n");
return (EXIT_FAILURE);
}
}
else
{
printf("Invalid string\n");
return (EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
You really need to decide what it is you want to do for which strtoul
and other library functions do not provide a better method. So far,
your code is incorrect (or, if you prefer, it has reduced
functionality).
Remove del for email
Jul 4 '08 #24
On 3 Jul, 19:56, pereges <Brol...@gmail.comwrote:
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
Jul 4 '08 #25
Default User wrote:
pete wrote:
>Default User wrote:
>>But not undefined behavior.
>It's a better way to write C90 code,
even if you don't intend it to be compiled as C99 code,


What does this have to do with what I said?
Nothing. There was nothing more to say on that topic.

I hijack threads here very frequently to discuss
what I want to discuss about the C programming language.

--
pete
Jul 4 '08 #26
Barry Schwarz wrote:
On Thu, 3 Jul 2008 11:56:06 -0700 (PDT), pereges <Br*****@gmail.com>
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 ? :

Code:

#include <stdio.h>
#include <string.h>

int main(void)
{
char s[50];
int i = 0;

gets(s);

You have to be trolling to still use this.
> while (isspace(s[i]))
i++;
while (isdigit(s[i]))
i++;
while (isspace(s[i]))
i++;
if (s[i] != '\0')
printf("\nIncorrect string\n");

If the input is "9 5", you will fail the string even though it meets
your verbal definition.
That misinterprets the definition. Following the first digit is " 5",
which is neither "only digits" nor "only whitespace", so fails to satisfy
his stated definition (assuming "till" means "until"). It doesn't admit to
digits and whitespace following the first digit. That precludes " 42 "
(digit and whitespace), "42" (digit, not digits), but not "402" or "4 ".

Regex, anyone?

--
Thad
Jul 4 '08 #27
pete <pf*****@mindspring.comwrote:
Default User wrote:
pete wrote:
Default User wrote:
>But not undefined behavior.
It's a better way to write C90 code,
even if you don't intend it to be compiled as C99 code,
What does this have to do with what I said?

Nothing. There was nothing more to say on that topic.

I hijack threads here very frequently to discuss
what I want to discuss about the C programming language.
Well, don't do that. This is not talk.ramble.endlessly. Start a new
thread.

Richard
Jul 7 '08 #28
In article <87************@bsb.me.uk>
Ben Bacarisse <be********@bsb.me.ukwrote:
>[Aside. I feel I must "come clean". Until today I did not know that
strtoul accepted "-123" as a valid number[1]. Of course it does the
right thing with it but you can't tell, from the result alone, that
the input was not 4294967173[2]. If I'd been more clued up on that at
the start, I'd have advised the use of strtol right from the get-go.]

[1] Well, I might have known. It seems a strangely familiar
discovery, but it was not up there at the front on my brain where it
was needed to give the best advice. The OP is validating input and,
for most application end users, C's interpretation of (unsigned
long)-123 is just baffling. strtoul is not the right tool.
[footnote 2 snipped] It probably is true that strtoul() is not
as commonly useful as strtol(), and I am not sure *why* strtoul
is specified as allowing explicit signs, but if you wish to
forbid signs, the method Peter Nilsson showed (elsethread) is
probably the simplest. That is, just call strtoul() as normal,
but add to the "number was valid" checks a call to strchr() to
check for '-' (and '+' as well, if you wish to forbid that too).

If you are going to check for more than one "forbidden" character
-- e.g., for both + and -, and/or for leading whitespace -- you
can use strpbrk(). That is, instead of:

/* Assumes:
"char *input" pointing to the input,
"char *ep" which need not be initialized,
"int base" which should be 10 or 0 or whatever,
"unsigned long result",
and of course the appropriate #include directives. */

errno = 0;
result = strtoul(input, &ep, base);
if ((result == ULONG_MAX && errno == ERANGE) || /* value too large */
ep == input || /* no value supplied (so result==0) */
*ep != '\0' || /* trailing junk after value */
strchr(input, '-') != NULL || /* contained leading - sign */
strchr(input, '+') != NULL /* contained leading + sign */) {
... do something about bad input ...
}

you can do:

if ((result == ULONG_MAX && errno == ERANGE) || ep == input ||
*ep != '\0' || strpbrk(input, "-+") != NULL)) {
... do something ...
}

If you want to reject whitespace, *and* want to handle locales,
the problem is a bit harder. While ' ', '\t', '\b', '\r', '\n',
and '\f' are all whitespace, there may be additional characters
for which isspace() would return true. In this case you cannot
easily use strchr() or strpbrk(); you will be better off with a
test for isspace(). (But you can just check the first character
since strtoul() allows only *leading* whitespace.)

(It is of course possible to do the "forbidden characters" test up
front, but since you must do the "value out of range" test *after*
calling strtoul() -- or indeed any of the strto* family -- and most
programs need not handle errors as fast as possible, it is safe
enough to pile them all up at the end like this.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: gmail (figure it out) http://web.torek.net/torek/index.html
Jul 10 '08 #29

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
by: linzhenhua1205 | last post by:
I want to parse a string like C program parse the command line into argc & argv. I hope don't use the array the allocate a fix memory first, and don't use the memory allocate function like malloc....
19
by: Paul | last post by:
hi, there, for example, char *mystr="##this is##a examp#le"; I want to replace all the "##" in mystr with "****". How can I do this? I checked all the string functions in C, but did not...
29
by: zoltan | last post by:
Hi, The scenario is like this : struct ns_rr { const u_char* rdata; }; The rdata field contains some fields such as :
15
by: Fariba | last post by:
Hello , I am trying to call a mthod with the following signature: AddRole(string Group_Nam, string Description, int permissionmask); Accroding to msdn ,you can mask the permissions using...
9
by: Michael D. Ober | last post by:
OK, I can't figure out a way to optimize the following VB 2005 code using StringBuilders: Public Const RecSize as Integer = 105 Private buffer As String Public Sub New() init End Sub...
1
by: kellysgirl | last post by:
Now what you are going to see posted here is both the set of instructions I was given..and the code I have written. The instructions I was given are as follows In this case, you will create...
3
by: WP | last post by:
Hello! I need some help with my program...it's supposed to read infix expressions line by line from stdin and each expression should be divided into operands and operators and added to a vector of...
6
by: James Arnold | last post by:
Hello, I am new to C and I am trying to write a few small applications to get some hands-on practise! I am trying to write a random string generator, based on a masked input. For example, given...
1
by: eyeore | last post by:
Hello everyone my String reverse code works but my professor wants me to use pop top push or Stack code and parsing code could you please teach me how to make this code work with pop top push or...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.