C/C++ Help
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
 
User Name:
Password:
Remember me
 
Go Back   Dev Articles Community ForumsProgrammingC/C++ Help

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Display Modes
 
Unread Dev Articles Community Forums Sponsor:
  #1  
Old May 17th, 2006, 05:13 AM
jaro jaro is offline
Contributing User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Nov 2005
Posts: 35 jaro User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 Day 6 h 16 m 44 sec
Reputation Power: 4
Send a message via Yahoo to jaro
Checking if string is a number or not

I've made a function that determines if character string is a number or not.Using only isdigit().

Here is my sample code
Code:
#include <string.h>
#include <stdio.h>
#include <ctype.h>

int isNumber(char str[])
{
	int withDecimal =0,isNegative=0 ,i=0;
	int len = strlen(str);

	for (i=0; i<len; i++)
	{
		if (!isdigit(str[i])) // if1
		{
			if (str[i] == '.')
			{
				if(withDecimal){
					return 0;
				}
				withDecimal =1;
			}
			else if (str[i] == '-')
			{
				if(isNegative){
					return 0;
				}

				if(i==0){
					isNegative = 1;
				}else{
					return 0;
				}

			}else{
				return 0;
			}
		} //end if1
	}// end for
	return 1;
}

int main(){
	
	//for testing purpose only
	char charNum[10][15] = {
		"100.23" ,
		"-200.456",
		"200..",
		"..200",
		"4.9.9.6",
		"--500",
		"500--",
		"59-52-6",
		"50.69-5",
		"5000"
	};

	int cntr = 0;

		for(cntr=0; cntr<10; cntr++){
			printf("%s\t\t", charNum[cntr]);

			if(isNumber(charNum[cntr])){
				printf("is a number!\n");
			}else{
				printf("NOT a NUMBER!\n");
			}
		}

}


and here is the output
Code:
100.23          is a number!
-200.456        is a number!
200..           NOT a NUMBER!
..200           NOT a NUMBER!
4.9.9.6         NOT a NUMBER!
--500           NOT a NUMBER!
500--           NOT a NUMBER!
59-52-6         NOT a NUMBER!
50.69-5         NOT a NUMBER!
5000            is a number!


as you can see. The function works fine.But to be on the safe side.I need to know your reaction on the function, whether it needs to improve on some aspects (memory utilization or something).

regards,
Jaro

Reply With Quote
  #2  
Old May 17th, 2006, 02:09 PM
ubergeek ubergeek is offline
Contributing User
Dev Articles Novice (500 - 999 posts)
 
Join Date: Jan 2005
Posts: 600 ubergeek User rank is Private First Class (20 - 50 Reputation Level)ubergeek User rank is Private First Class (20 - 50 Reputation Level) 
Time spent in forums: 2 Days 22 h 40 m 27 sec
Reputation Power: 5
Send a message via AIM to ubergeek
looks good, nice job. it seems like you're looking for nitpicky complaints, so here you are:
1. isNegative and withDecimal would probably be better as bool types, because (a) you test them as such in if statements and (b) they aren't holding numbers, just a yes/no flag, so a bool would be more intuitive/readable
2. technically, you use strlen() as well as isdigit()
3. this is purely your preference, to make the function more useful, you could have it return the number if it is a number--the issue is then how to indicate failure. you could have it return a boolean and take a result parameter as a pointer/reference to an int.

nice job though!

Reply With Quote
  #3  
Old May 18th, 2006, 03:21 AM
jaro jaro is offline
Contributing User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Nov 2005
Posts: 35 jaro User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 Day 6 h 16 m 44 sec
Reputation Power: 4
Send a message via Yahoo to jaro
Quote:
Originally Posted by ubergeek
looks good, nice job. it seems like you're looking for nitpicky complaints, so here you are:
1. isNegative and withDecimal would probably be better as bool types, because (a) you test them as such in if statements and (b) they aren't holding numbers, just a yes/no flag, so a bool would be more intuitive/readable
2. technically, you use strlen() as well as isdigit()
3. this is purely your preference, to make the function more useful, you could have it return the number if it is a number--the issue is then how to indicate failure. you could have it return a boolean and take a result parameter as a pointer/reference to an int.

nice job though!



Actually the code has lots of bugs.And these are as follows.
".-" , "-." , "." and "-" are considered numbers.
"+1.234E-05" is considered as not a number.

First I tried to solve the ".-" , "-." , "." and "-" issues.And what I've got is a isNumber() that has the greatest number of if else condition that I ever done. And another issue arrsises the "100.3-" is considered to be a number. And I haven't even started yet on the "+1.234E-05" issue.

Furtunately a kind person poited me into using the strtod().

After quick reading on how to use/implement strtod().

so here's the code with strtod().Suprisingly the strtod() made things lot easier.

Code:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

char errorNum[20]="";
char tempVal[100]="";

int isNumber(const char str[]){

	char *ok;
	
	strtod(str,&ok);

	/*	
	if(!isspace(*str)){		// check for leading whitespace,
		if(strlen(ok)==0){
			return 1;
		}else{
			return 0;
		}
	}else{
		return 0;
	}
	*/

	return !isspace(*str) && strlen(ok)==0;
}


int main(){
	
	//for testing purpose only
	char charNum[14][15] = {
		"00100" ,
		"-00200",
		"+030",
		"-040.30",
		"-000.35",
		" 50",
		"50 ",
		"char",
		"200.003-",
		".-",
		"-",
		".",
		"+1.234E-05",
		"-6.789E+10"
	};
	
	int cntr = 0;
	
		for(cntr=0; cntr<14; cntr++){

			printf("[%s]\t\t", charNum[cntr]);

			if(isNumber(charNum[cntr])){
				printf("is a number!\n");
			}else{
				printf("NOT a NUMBER!\n");
			}
		}

}


OUTPUT
Code:

[00100]         is a number!
[-00200]        is a number!
[+030]          is a number!
[-040.30]       is a number!
[-000.35]       is a number!
[ 50]           NOT a NUMBER!
[50 ]           NOT a NUMBER!
[char]          NOT a NUMBER!
[200.003-]      NOT a NUMBER!
[.-]            NOT a NUMBER!
[-]             NOT a NUMBER!
[.]             NOT a NUMBER!
[+1.234E-05]    is a number!
[-6.789E+10]    is a number!


I know that the final revision dosen't use isdigit().The reason why isdigit() is use in the first place is that this is the only function that I know (which is portable) that can detect if (in this case) a character is a number or not. And I just found out that strtod() is also portable.

also notice in the isNumber().there are some code that are commented out, this is purely for reading purepuses only.

So I guess the lesson that I've learn from this program is that I need to know all the standard C function, thier meaning and ussage.
and also lots of people have commented on the way that I've written the code, so I guess that would be it.

Regards,
Jaro

Last edited by jaro : May 18th, 2006 at 05:57 AM. Reason: edit some sentences

Reply With Quote
Reply

Viewing: Dev Articles Community ForumsProgrammingC/C++ Help > Checking if string is a number or not


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


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

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump



 Free IT White Papers!
 
How to Present Effectively Online
This white paper offers practical and actionable advice on the key steps that any presenter should consider as they plan and execute a Webinar or online meeting.

Request Your Free Technology Downloads!
 
Open Source Security Myths
Open Source Software (OSS) is computer software whose source code is available to the general public with relaxed or non-existent intellectual property restrictions (or arrangement such as the public domain), and is usually developed with the input of many contributors.

Request Your Free Technology Downloads!
 
Power and Cooling Capacity Management for Data Centers
This paper describes the principles for achieving power and cooling capacity management.

Request Your Free Technology Downloads!
 
Scalable, Fault-Tolerant NAS for Oracle - The Next Generation
For several years NAS has been evolving as a storage alternative for Oracle databases, and for good reason: NAS is quite often the simplest, most cost-effective storage approach for Oracle. Learn about the benefits that HP's approach to scalable NAS brings to Oracle environments in this comprehensive white paper.

Request Your Free Technology Downloads!
 
Understanding Web Application Security Challenges
This white paper discusses many common threats and preventive measures for Web application security, and explains what you can do to help protect your organization.

Request Your Free Technology Downloads!
 

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 




© 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
Stay green...Green IT