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_FAILU RE);
}
scanf("%s",got) ;
while( (*got)++ != '\0')
{
if(*got != ('0' - '9'))
{
printf("error\n ");
break;
}
else
printf("%s\n",g ot);
}
return 0;
} 13 1804
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_FAILU RE);
}
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",g ot);
}
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
fool wrote:
char *got;
got = malloc(sizeof (char));
if(got == NULL)
{
got = malloc(sizeof (char));
if(got == NULL)
exit(EXIT_FAILU RE);
}
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
"fool" <fo**@fool.comw rote in message
news:MP******** *************** *@news.sunsite. dk...
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_FAILU RE);
}
scanf("%s",got) ;
while( (*got)++ != '\0')
{
if(*got != ('0' - '9'))
{
printf("error\n ");
break;
}
else
printf("%s\n",g ot);
}
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.
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>
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?
On 22 Dec 2006 00:58:53 -0800, "Scorpio" <av*******@gmai l.comwrote:
> 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
"Scorpio" <av*******@gmai l.comwrote:
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
Richard Bos wrote:
"Scorpio" <av*******@gmai l.comwrote:
>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>
>Richard Bos wrote:
>>... strtol() is better [than atoi()] - it doesn't have undefined behaviour on overflow.
In article <45************ ***@yahoo.com>
CBFalconer <cb********@mai neline.netwrote :
>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_trail ing_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_lead ing_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_lea ding_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. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Julia Briggs |
last post by:
Hello, trying to create logic tests against a string allowing someone
to enter a certain character once or twice into a form consecutively,
but not twice seperated between other characters....
so,
hello##there (ok)
hello#there (ok)
#hello#there (no)
##hello#there (no)
|
by: stanlo |
last post by:
hi to everyone, this is still a follow up of my project ,mathematical
expression.this project is meant to evaluate mathemtical expressions
with oparators,+,-,*,/.more than two operands can be done, eg it should
be able to do,1+9-45*7/12,or 4* 5+6*21.from reading and help from you i
have been able to write the program.but my problem is to process the
string of the input.i.e given for example an input string, 12+6*65/7,
you know i have to...
|
by: Nader |
last post by:
Hello all,
In C# string is a reference type but I learned that string is different from
other reference types such as class. For example, if you pass a string
argument to a method and then change the value in that method the
modification will not be visible outside the method. However this is not
true for classes. In my example I am not using ref keyword.
Thanks for feedback.
|
by: JAKE |
last post by:
I'm pretty new to ansi c and I'm stuck I'm trying to assemble a string
in a called function. I need to send it three different data types and
return the assembled string. I've been getting errors such as...
28 C:\Dev-Cpp\assemble.c conflicting types for 'assemble'
3 C:\Dev-Cpp\assemble.c previous declaration of 'assemble' was here
30 C:\Dev-Cpp\assemble.c syntax error before "a"
here's what I have so far....
|
by: zhege |
last post by:
I am a beginner of C++;
I have a question about the std:string and std:cout class;
Two pieces of code:
--------------------------------
#include <iostream>
#include <string>
using namespace std;
int main()
| |
by: Robert Seacord |
last post by:
The SEI has published CMU/SEI-2006-TR-006 "Specifications for Managed
Strings" and released a "proof-of-concept" implementation of the managed
string library.
The specification, source code for the library, and other resources
related to managed strings are available for download from the CERT web
site at:
http://www.cert.org/secure-coding/managedstring.html
|
by: John |
last post by:
Hi,
I'm a beginner is using C# and .net.
I have big legacy files that stores various values (ints, bytes, strings) and want to read them into
a C# programme so that I can store them in a database. The files are written by a late 1980's PC
Pascal programme, for which I don't have the source code. I've managed to reverse engineer the file
format.
The strings are stored as Ascii in the file, with the first byte indicating the string...
|
by: SMichal |
last post by:
Hi, how can I parse string "? 20.000" to double ?
|
by: Chelong |
last post by:
hey
now i have a problem,for me a c++ beginner.so i need ur help?
here i have a text file from the copy of excel data,like this:
=======================================================apple====pear===
First XXZHYY3A(Lily) 0 20 8 0 0 7 XXZHYY3AŁ¨LilyŁ© 8 0 0 8 8 8
XXZHYY3AŁ¨huangŁ© 7 0 0 7 7 5 Senco XXZHYY3B(huang) 22 22 3.65222
22 4 XXZHYY11AŁ¨chengŁ© 70¸ö 60 9.96 7 70...
|
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...
|
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...
| |
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...
|
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,...
|
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
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
| |