473,799 Members | 3,006 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 #1
28 2200
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("\nIncor rect 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....@gm ail.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....@gm ail.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....@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]))
{
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....@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) :
<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....@gm ail.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....@gm ail.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 "autoprototypin g" 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....@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) :
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

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

Similar topics

19
20591
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
78847
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
4271
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
3085
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
1935
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
3064
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
2107
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
3519
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
4410
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
9688
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9546
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
10491
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10268
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...
0
10031
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
9079
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
6809
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5593
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3762
muto222
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.