473,499 Members | 1,886 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

checking for numbers

H.
What's the easiest way to check if an argument entered at the command
line is a number?

I know that one way would be to treat the argument as a character
string, and then manually check each character to make sure it is 0
through 9, with the first digit not being 0.

But this seems like such basic functionality, I'm wondering if I'm
missing something.

Jan 28 '07 #1
15 1611
On Jan 28, 3:29 pm, "H." <hbe...@gmail.comwrote:
What's the easiest way to check if an argument entered at the command
line is a number?

I know that one way would be to treat the argument as a character
string, and then manually check each character to make sure it is 0
through 9, with the first digit not being 0.

But this seems like such basic functionality, I'm wondering if I'm
missing something.
What is your definition of a number? Does it have to be an integer or
can it be a decimal number? Can the number be negative? Can it be of
arbitrary size of does it need to fall into the range of a specific
type? Can it start with space characters? What exactly are you
trying to do?
You might find the strto* functions helpful, otherwise you will need
to clarify your definition of a number.

Robert Gamble

Jan 28 '07 #2
"H." <hb****@gmail.comwrites:
What's the easiest way to check if an argument entered at the command
line is a number?

I know that one way would be to treat the argument as a character
string, and then manually check each character to make sure it is 0
through 9, with the first digit not being 0.

But this seems like such basic functionality, I'm wondering if I'm
missing something.
Why not leading zeros? You can try strspn:

#include <stdio.h>
#include <string.h>
int main (void)
{
char s[] = "3345567899005431234";
char valid[] = "0123456789";

size_t res = strspn (s, valid);
if ( res != strlen (s) )
printf("Invalid argument: %s\n", s);

return 0;
}
--
espen
Jan 28 '07 #3
H. wrote:
What's the easiest way to check if an argument entered at the command
line is a number?

I know that one way would be to treat the argument as a character
string, and then manually check each character to make sure it is 0
through 9, with the first digit not being 0.

But this seems like such basic functionality, I'm wondering if I'm
missing something.
Best bets: strtol(), strtoul(), or strtod(), depending on
the kind of "number" you want to accept. Note that these will
accept some forms of "number" that you might not want: digit
strings with leading spaces, for example, or with a leading
minus sign. But in addition to checking for digits (and such),
they'll also check the range of the converted value: a string
of a thousand consecutive nines is "numeric," but you might not
want to consider it a "number."

Another possibility is sscanf(), but I feel the strtoxx()
functions are more direct.

--
Eric Sosman
es*****@acm-dot-org.invalid
Jan 28 '07 #4
On Jan 28, 3:52 pm, Eric Sosman <esos...@acm-dot-org.invalidwrote:
H. wrote:
What's the easiest way to check if an argument entered at the command
line is a number?
I know that one way would be to treat the argument as a character
string, and then manually check each character to make sure it is 0
through 9, with the first digit not being 0.
But this seems like such basic functionality, I'm wondering if I'm
missing something. Best bets: strtol(), strtoul(), or strtod(), depending on
the kind of "number" you want to accept. Note that these will
accept some forms of "number" that you might not want: digit
strings with leading spaces, for example, or with a leading
minus sign. But in addition to checking for digits (and such),
they'll also check the range of the converted value: a string
of a thousand consecutive nines is "numeric," but you might not
want to consider it a "number."

Another possibility is sscanf(), but I feel the strtoxx()
functions are more direct.
The scanf functions are almost always a poor choice for converting
numbers because if the number is outside the range of the expected
type it will always invoke undefined behavior.

Robert Gamble

Jan 28 '07 #5
On Jan 29, 8:04 am, "Robert Gamble" <rgambl...@gmail.comwrote:
On Jan 28, 3:52 pm, Eric Sosman <esos...@acm-dot-org.invalidwrote:
H. wrote:
What's the easiest way to check if an argument entered at the command
line is a number?
Best bets: strtol(), strtoul(), or strtod(), depending on
the kind of "number" you want to accept. ...

Another possibility is sscanf(), but I feel the strtoxx()
functions are more direct.

The scanf functions are almost always a poor choice for converting
numbers
You mean programmers almost always make poor choices of the way
they invoke scanf.
because if the number is outside the range of the expected
type it will always invoke undefined behavior.
No. For example, consider: int i, r = scanf("%4d", &i);

--
Peter

Jan 28 '07 #6
>What's the easiest way to check if an argument entered at the command
>line is a number?
Define "a number".
>I know that one way would be to treat the argument as a character
string, and then manually check each character to make sure it is 0
through 9, with the first digit not being 0.
You forgot the leading minus sign. And perhaps leading whitespace.
And perhaps a leading 0 or 0x signifying the base.
>But this seems like such basic functionality, I'm wondering if I'm
missing something.
strtol() and family will return in the pointer pointed at by its
second argument a pointer to the next character after the number
(if one was found). If that pointer is not null and points at a
string terminator, it's a valid number. If that pointer is not
null and points at characters such as a space, tab, comma, newline,
or whatever, it may or may not be something you consider valid. If
it points at something else wierd, like an underscore, it's probably
not valid.
Jan 28 '07 #7
On Jan 28, 5:22 pm, "Peter Nilsson" <a...@acay.com.auwrote:
On Jan 29, 8:04 am, "Robert Gamble" <rgambl...@gmail.comwrote:
On Jan 28, 3:52 pm, Eric Sosman <esos...@acm-dot-org.invalidwrote:
H. wrote:
What's the easiest way to check if an argument entered at the command
line is a number?
Best bets: strtol(), strtoul(), or strtod(), depending on
the kind of "number" you want to accept. ...
Another possibility is sscanf(), but I feel the strtoxx()
functions are more direct.
The scanf functions are almost always a poor choice for converting
number.
You mean programmers almost always make poor choices of the way
they invoke scanf.
The usefulness of scanf for converting numbers is quite limited if you
don't want to risk invoking undefined behavior. Tell me, what is the
proper way to invoke scanf to convert an int whose value may be any of
those that an int can represent without invoking undefined behavior
upon encountering a value that is not?
because if the number is outside the range of the expected
type it will always invoke undefined behavior.

No. For example, consider: int i, r = scanf("%4d", &i);
Well in that case the number being converted isn't outside the range
of the expected type now is it?

Robert Gamble

Jan 28 '07 #8
"H." <hb****@gmail.comwrote in message
news:11*********************@h3g2000cwc.googlegrou ps.com...
What's the easiest way to check if an argument entered at the command
line is a number?

I know that one way would be to treat the argument as a character
string, and then manually check each character to make sure it is 0
through 9, with the first digit not being 0.

But this seems like such basic functionality, I'm wondering if I'm
missing something.
First, you have to realize something about both users and numbers -- they
ARE out to get you. You can't turn your back on them, or they will conspire
and move against you. It is the same principle when bowling -- the 8 and 9
pins are shielded from your view by the other pins and they are conspiring
against you.

The safest approach to the problem you're describing is to write your own
function that maps from (string) to (valid, number). Proceed in two phases:

a)Force the string into the allowed character set (i.e. it should be only
digits).

b)Use a bit of FSA theory to parse the string. You need to have a firm idea
of what constitutes a "number" for your application, and it is then easy to
devise an automaton approach to parse it.

Generally, expect to write about 100 lines of code. In goes the string.
Out comes an error/success code and a number.
--
David T. Ashley (dt*@e3ft.com)
http://www.e3ft.com (Consulting Home Page)
http://www.dtashley.com (Personal Home Page)
http://gpl.e3ft.com (GPL Publications and Projects)
Jan 29 '07 #9
"H." wrote:
>
What's the easiest way to check if an argument entered at the
command line is a number?

I know that one way would be to treat the argument as a character
string, and then manually check each character to make sure it is
0 through 9, with the first digit not being 0.

But this seems like such basic functionality, I'm wondering if
I'm missing something.
A simple sequence to use is:

int i;

if (1 != sscanf(argv[i], "%d", &i)) puts("not a number");
else {
carryonjack();
}

provided you have first ensured that argv[i] exists by checking the
value of argc.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
Jan 29 '07 #10
Gordon Burditt wrote:

[Gordon, it might amuse you to see what Thunderbird's spell-
checker does with your surname.]
>What's the easiest way to check if an argument entered at the command
line is a number?

Define "a number".
>I know that one way would be to treat the argument as a character
string, and then manually check each character to make sure it is 0
through 9, with the first digit not being 0.

You forgot the leading minus sign. And perhaps leading whitespace.
And perhaps a leading 0 or 0x signifying the base.
Therein lies a user interface trap. If you specify zero
as the base for strtol() or its brethren, they will interpret
a leading 0 or 0x as indicating base eight or sixteen. If a
program accepts input from humans who are not C programmers
this is almost certainly a Bad Thing: Ordinary people expect
leading zeroes to be place-holders and nothing more. If you
use strtoul() this way to accept telephone numbers in three
parts, for example, you'll have trouble with 781 424 0116: it
will be accepted, but when you dial you'll reach 781 424 0078.

Recommendation: "Almost always" specify ten explicitly as
the base for strtoxx(). The extra flexibility gained by using
zero is "almost always" unwanted and potentially harmful.

--
Eric Sosman
es*****@acm-dot-org.invalid
Jan 29 '07 #11
Eric Sosman wrote:
Gordon Burditt wrote:

[Gordon, it might amuse you to see what Thunderbird's spell-
checker does with your surname.]
I had to try it myself, that truly was amusing ;)

Jeff
Jan 29 '07 #12
H.
int i;

if (1 != sscanf(argv[i], "%d", &i)) puts("not a number");
else {
carryonjack();
}
But aren't you assuming here that the digits are all 1s?

Jan 29 '07 #13
In article <11**********************@k78g2000cwa.googlegroups .com>,
H. <hb****@gmail.comwrote:
>
> int i;

if (1 != sscanf(argv[i], "%d", &i)) puts("not a number");
else {
carryonjack();
}

But aren't you assuming here that the digits are all 1s?
No, sscanf() returns the -number- of successfully matched items,
0 if no items were successfully matched, and EOF if there is
end of input string before the first character.

--
There are some ideas so wrong that only a very intelligent person
could believe in them. -- George Orwell
Jan 29 '07 #14
On Jan 28, 9:24 pm, CBFalconer <cbfalco...@yahoo.comwrote:
"H." wrote:
What's the easiest way to check if an argument entered at the
command line is a number?
I know that one way would be to treat the argument as a character
string, and then manually check each character to make sure it is
0 through 9, with the first digit not being 0.
But this seems like such basic functionality, I'm wondering if
I'm missing something.A simple sequence to use is:

int i;

if (1 != sscanf(argv[i], "%d", &i)) puts("not a number");
else {
carryonjack();
}

provided you have first ensured that argv[i] exists by checking the
value of argc.
A better solution would be to use one of the strto* functions as they
don't invoke UB if the number is too large and allow you to more
easily determine if the data after the conversion is valid. For
example, the string "123abc" will be deemed a number by the presented
sscanf solution whereas strtol can set a pointer to the "a" in the
string which the program can use to examine the data after the number
and determine if it is valid.

Robert Gamble

Jan 29 '07 #15
Jeffrey Stedfast <st******@comcast.netwrote:
Eric Sosman wrote:
Gordon Burditt wrote:

[Gordon, it might amuse you to see what Thunderbird's spell-
checker does with your surname.]

I had to try it myself, that truly was amusing ;)
I don't have an up-to-date Thunderbird here, but let me guess: Gordon
Bennett!?

Richard
Jan 30 '07 #16

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

Similar topics

7
7548
by: - ions | last post by:
I have created a JComboBox with its Items as a list of "M" numbers ie. M1,M2,M3.......throgh too M110 (thes are the messier objects, a catolouge of deep sky objects) the user selects of of these...
5
11030
by: William Payne | last post by:
Hello, I am in the process of converting a C++ program to a C program. The user of the program is supposed to supply an integer on the command line and in the C++ version of the program I was using...
2
3692
by: Marlene Stebbins | last post by:
I am entering numbers into my program from the command line. I want to check whether they are > INT_MAX. Sounds simple, but I've discovered that if(x <= INT_MAX) { /* use x in some calculation...
7
2622
by: Hulo | last post by:
In a C program I am required to enter three numbers (integers) e.g. 256 7 5 on execution of the program. C:\> 256 7 5 There should be spaces between the three numbers and on pressing "enter",...
3
3686
by: LSW | last post by:
I'm using Borland Turbo C++ 3.0 to develop an embedded system to shift data around a network. At the moment we receive a string of bytes over a serial line and reassemble them into floating point...
125
6465
by: jacob navia | last post by:
We hear very often in this discussion group that bounds checking, or safety tests are too expensive to be used in C. Several researchers of UCSD have published an interesting paper about this...
4
7904
by: H.S. | last post by:
Hello, I am trying out a few methods with which to test of a given number is practically zero. as an example, does the following test correctly if a given number is zero within machine...
1
3309
by: AndyB | last post by:
I have found a lot of material on removing duplicates from a list, but I am trying to find the most efficient way to just check for the existence of duplicates in a list. Here is the best I have...
27
2256
by: Aaron Hsu | last post by:
Hey all, After seeing the Secure version I/O functions thread, it occured to me that maybe not everyone agrees with the almost universal adage that I have heard. I have Always been told that...
21
11345
by: ningxin | last post by:
Hi, i am currently taking a module in c++ in the university, and was given an assignment. because i have no prior background on the subject, everything is kind of new to me. i have tried for quite...
0
7131
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
7174
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,...
1
6894
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...
0
7388
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...
0
5470
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,...
0
4600
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...
0
3099
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
3091
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1427
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 ...

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.