Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > if string is a number (beginner)

Reply
Thread Tools

if string is a number (beginner)

 
 
fool
Guest
Posts: n/a
 
      12-22-2006
Dear group,
I want to check if the given string is a number. If any value is
inputed other than a number then error. The following is not the correct
solution. Can some one tell me any link for the above task? Pls just
don't give the code. Thanks.

#include<stdio.h>
#include<stdlib.h>
int main(void)
{
char *got;
got = malloc(sizeof (char));
if(got == NULL)
{
got = malloc(sizeof (char));
if(got == NULL)
exit(EXIT_FAILURE);
}

scanf("%s",got);
while( (*got)++ != '\0')
{
if(*got != ('0' - '9'))
{
printf("error\n");
break;
}
else
printf("%s\n",got);
}
return 0;
}
 
Reply With Quote
 
 
 
 
Default User
Guest
Posts: n/a
 
      12-22-2006
fool wrote:

> Dear group,
> I want to check if the given string is a number. If any value is
> inputed other than a number then error. The following is not the
> correct solution. Can some one tell me any link for the above task?
> Pls just don't give the code. Thanks.
>
> #include<stdio.h>
> #include<stdlib.h>
> int main(void)
> {
> char *got;
> got = malloc(sizeof (char));


This allocates exactly one character's worth of space. That's pretty
useless. Why are you even dynamically allocating memory?

> if(got == NULL)
> {
> got = malloc(sizeof (char));


If it failed before, try again? Why?

> if(got == NULL)
> exit(EXIT_FAILURE);
> }
>
> scanf("%s",got);


Your allocated memory does not enough room to store any string longer
than the empty string. The scanf() function as used above has no way to
limit the number of characters entered. If it's longer than the empty
string, then Undefined Behavior results.

> while( (*got)++ != '\0')


You dereferenced the pointer, then incremented the result. I doubt
that's what you wanted.

> {
> if(*got != ('0' - '9'))


What do you think that minus sign does? Whatever, what it actually does
is subract the numerical value of the two characters, which will result
in -9.

It doesn't matter, because if the loop executed at all (not the empty
string) then you had UB before, and more now.

> {
> printf("error\n");
> break;
> }
> else
> printf("%s\n",got);
> }
> return 0;
> }



What book are you using?


Here's a brief snippet (the comments are for you to think about):

char buffer[80]; /* magic numbers are bad, how would you fix that? */
int i;

fgets(buffer, sizeof buffer, stdin);
/* what if more than that is entered? */

for(i = 0; buffer[i]; i++) /* why this instead of the while? */
{
if (buffer[i] < '0' || buffer[i] > '9') /* can you decode this? */
{
printf("error\n");
break;
}
}


Brian
 
Reply With Quote
 
 
 
 
Ulrich Eckhardt
Guest
Posts: n/a
 
      12-22-2006
fool wrote:
> char *got;
> got = malloc(sizeof (char));
> if(got == NULL)
> {
> got = malloc(sizeof (char));
> if(got == NULL)
> exit(EXIT_FAILURE);
> }


This allocation looks strange. You retry without anything changing and
expect that to then yield a result - it won't happen. If a malloc failure
can't be recovered from, I'd suggest using xalloc. This is not a library
function like malloc but a wrapper around it that tries to allocate the
memory and, in case of failure, writes an error message to stderr and
exit()s. Using this helps you remove those 6 lines of error-handling code
that distracts from the real logic of the program.
Also, you only allocate space for a single character and that size is 1, by
definition (i.e. the standard says that sizeof (char)==1).

> scanf("%s",got);


Bad idea, you are reading an unbounded string into an array of size 1.
Well, in fact this is a bad idea regardless of how long the array is, you
should never use unbounded function parameters. You can tell scanf how
long the target string is. Also, there is fgets() (be sure to read the
warnings for gets(), which looks more convenient at first!) which only
does input as a string.

> while( (*got)++ != '\0')


This is not what you want. Try this on a loop with a normal character
literal and step through it with a debugger.

> if(*got != ('0' - '9'))


Sorry, but while this looks intuitive, C doesn't let you. The '0' and '9'
are treated as integers, and the minus sign in between just yields the
difference between them. What you need is a check that the character is at
least zero and at most nine. There is also a library function isdigit(),
but firstly that is difficult to use correctly and secondly it also
includes the minus and plus signs, IIRC.

Lastly, in the while() expression, it seems like you already moved to the
next character. I suggest printing the current character as integer inside
your loop. That way you will better understand what's going on.

Uli

 
Reply With Quote
 
Malcolm
Guest
Posts: n/a
 
      12-22-2006



"fool" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> Dear group,
> I want to check if the given string is a number. If any value is
> inputed other than a number then error. The following is not the correct
> solution. Can some one tell me any link for the above task? Pls just
> don't give the code. Thanks.
>
> #include<stdio.h>
> #include<stdlib.h>
> int main(void)
> {
> char *got;
> got = malloc(sizeof (char));
> if(got == NULL)
> {
> got = malloc(sizeof (char));
> if(got == NULL)
> exit(EXIT_FAILURE);
> }
>
> scanf("%s",got);
> while( (*got)++ != '\0')
> {
> if(*got != ('0' - '9'))
> {
> printf("error\n");
> break;
> }
> else
> printf("%s\n",got);
> }
> return 0;
> }


strtol() for integers, or strtod, for floating-point numbers, are your
friend.
Unfortunately for newbies they take a pointer to a pointer to indicate the
end of the digits that can be interpreted as numbers.
However the idea is not too complicated. if the end pointer points to 0, the
end of string character, you have a valid number. If it is a non-digit, you
might want to throw the number out. If the end pointer is at the beginning
of the string, there were no digits at the beginning of the string so you
must throw the input out.
Watch for whitespace, by the way.
--
www.personal.leeds.ac.uk/~bgy1mm
freeware games to download.


 
Reply With Quote
 
CBFalconer
Guest
Posts: n/a
 
      12-22-2006
fool wrote:
>
> I want to check if the given string is a number. If any value is
> inputed other than a number then error. The following is not the
> correct solution. Can some one tell me any link for the above
> task? Pls just don't give the code. Thanks.


You don't need any intermediate string. Just getc, together with
routines to skip blanks and the tests available in ctype.h. If you
want a demonstration see txtinput.c in txtio.zip, routine readxwd,
available at:

<http://cbfalconer.home.att.net/download/>

Some things in that zip are undergoing revision, but that routine
is solid. The changes have to do with signed input and arranging
for readxwd to follow normal unsigned behaviour for overflows. At
exit readxwd returns the termination char, so you can easily check
that is an allowable one. In particular if it is a '.' or a 'e'
(or 'E') you may have found a real value (double or float).

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>


 
Reply With Quote
 
Scorpio
Guest
Posts: n/a
 
      12-22-2006

fool wrote:
> Dear group,
> I want to check if the given string is a number. If any value is
> inputed other than a number then error. The following is not the correct
> solution. Can some one tell me any link for the above task?


Why not just use the function atoi from<stdlib.h> ?

 
Reply With Quote
 
jaysome
Guest
Posts: n/a
 
      12-22-2006
On 22 Dec 2006 00:58:53 -0800, "Scorpio" <(E-Mail Removed)> wrote:

>
>fool wrote:
>> Dear group,
>> I want to check if the given string is a number. If any value is
>> inputed other than a number then error. The following is not the correct
>> solution. Can some one tell me any link for the above task?

>
>Why not just use the function atoi from<stdlib.h> ?


Because with atoi() there is not a guaranteed way to distiguish
between an integer value of 0 and an invalid integer value--both may
return 0.

#include<stdio.h>
#include<stdlib.h>
int main(void)
{
printf("atoi(\"0\") == %d\n", atoi("0"));
printf("atoi(\"A\") == %d\n", atoi("A"));
return 0;
}

Others have properly suggested the use of the strto* functions.

Happy Holidays
--
jay
 
Reply With Quote
 
Richard Bos
Guest
Posts: n/a
 
      12-22-2006
"Scorpio" <(E-Mail Removed)> wrote:

> fool wrote:
> > I want to check if the given string is a number. If any value is
> > inputed other than a number then error. The following is not the correct
> > solution. Can some one tell me any link for the above task?

>
> Why not just use the function atoi from<stdlib.h> ?


Because strtol() is better - it doesn't have undefined behaviour on
overflow.

Richard
 
Reply With Quote
 
CBFalconer
Guest
Posts: n/a
 
      12-22-2006
Richard Bos wrote:
> "Scorpio" <(E-Mail Removed)> wrote:
>> fool wrote:
>>
>>> I want to check if the given string is a number. If any value is
>>> inputed other than a number then error. The following is not the
>>> correct solution. Can some one tell me any link for the above task?

>>
>> Why not just use the function atoi from<stdlib.h> ?

>
> Because strtol() is better - it doesn't have undefined behaviour on
> overflow.


Not quite. strtoul won't detect the out-of-range input of "-1",
for example. It makes the mistake of incorporating the - into the
number parsing. I want to know if the user has tried to stuff
something outside the principal range into the variable.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>


 
Reply With Quote
 
Chris Torek
Guest
Posts: n/a
 
      12-22-2006
>Richard Bos wrote:
>>... strtol() is better [than atoi()] - it doesn't have undefined
>>behaviour on overflow.


In article <(E-Mail Removed)>
CBFalconer <(E-Mail Removed)> wrote:
>Not quite. strtoul won't detect the out-of-range input of "-1",
>for example.


This is not "out of range", by definition. By strtoul()'s definition,
admittedly. If this disagrees with your own definition, it is
easy enough to prohibit a minus sign.

If you want to allow '-':

char buf[N];
char *ep;
int base;
unsigned long result;
...
errno = 0;
result = strtoul(buf, &ep, base);
if (result == ULONG_MAX && errno == ERANGE)
overflow();
else if (*ep != NULL)
there_was_trailing_stuff();
else
all_is_well();

To prohibit the '-', augment the strtoul() call with, e.g.:

if (buf[strspn(buf, " \t\n\r\b\v")] == '-')
there_is_a_leading_minus();
else if ((result = strtoul(buf, &ep, base)) == ULONG_MAX && errno == ERANGE)
... as before ...

or you can check for a '-' character after calling strtoul():

char *minusp;
...
result = strtoul(buf, &ep, base);
minusp = strchr(buf, '-');
if (minusp != NULL && (ep == NULL || minusp < ep))
there_was_a_leading_minus();
else if (result == ULONG_MAX && errno == ERANGE)
... as before ...

Of course, strtoul() could have been defined to prohibit signs
(plus and/or minus), and callers could explicitly allow them; or
it could even have taken flags indicating how to treat signs; but
this is the situation we have now, so code like the above will
handle it.
--
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: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Converting a number back to it's original string (that was hashed togenerate that number) Ferrous Cranus Python 7 01-23-2013 03:30 PM
convert string number to real number - ValueError: invalid literal davidj411 Python 11 05-29-2008 12:02 AM
OT: Number Nine, Number Nine, Number Nine FrisbeeŽ MCSE 37 09-26-2005 04:06 PM
HELP - how to convert a string representation of a number to a number ? cpptutor2000@yahoo.com C++ 5 05-21-2005 05:56 PM
Interrogating string for number of characters, response.writing identical number of characters on new line Ken Fine ASP General 2 02-05-2004 03:40 AM



Advertisments