473,811 Members | 2,038 Online
Bytes | Software Development & Data Engineering Community
+ 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("\nIncor rect 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
28 2204
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("\nIncor rect 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....@gm ail.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("\nIncor rect 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*****@mindsp ring.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.end lessly. 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
20592
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. who can give me some ideas? The following is my program, but it has some problem. I hope someone would correct it. //////////////////////////// //Test_ConvertArg.c ////////////////////////////
19
78850
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 find one.
29
4276
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
3086
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 pipe symbol .for example you can use something like this AddRole("My Group", "Test", 0x10000000|0x00000002);
9
1937
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 Public Sub New(ByVal value As String)
1
3066
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 a Visual Basic 2005 solution that manipulates strings. It will parse a string containing a list of items within a text box and put the individual items into the list box. It will build the textbox string by putting the list box items together into a...
3
2108
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 strings. So if we read one line that holds "1+2" the vector should afterwards hold the strings "1", "+" and "2". Valid operators are +, -, * and / meaning they are of length 1. Valid operands are ints >= 0 meaning they can stretch over several...
6
3520
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 the string: "AAANN" it would return a string containing 3 alphanumeric characters followed by 3 digits. This part I have managed:) I would now like to add some complexity to this, such as repetitions and grouping. For example, I'd like to have...
1
4411
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 Stack code and parsing code my professor i does not like me using buffer reader on my code and my professor did even give me an example code for parsing as well as pop push top or Stack code and i don't know how to do this code into parsing and pop push...
0
9605
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10389
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10402
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10135
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9205
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5554
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5692
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4339
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 we have to send another system
3
3018
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.