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: 5
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: 6
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: 5
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!
 
Create the Optimal Architecture for your Critical Applications
Warburton's the largest independently owned bakery in the UK faced a number of difficult challenges in providing the most robust yet efficient IT infrastructure for their organization's success. IBM's services combined with their xSeries servers created the perfect platform for their SAP environment with sufficient flexibility, and did so in very time effective fashion.

Request Your Free Technology Downloads!
 
Five Best Practices for Deploying a Successful Service-Oriented Architecture
This white paper describes the benefits you can expect with SOA, and how IBM can help take your business there.

Request Your Free Technology Downloads!
 
Gartner Magic Quadrant for Application Delivery Controllers
Gartner summarizes its view on Application Delivery Controllers, evaluates strengths and weaknesses of solutions, and provides Magic Quadrant reporting for a quick comparison across all vendors. Learn from Gartner how you can benefit from an all-in-one device like Citrix NetScaler that delivers the highest levels of availability, performance and security.

Request Your Free Technology Downloads!
 
Knowledge is Power
What you don't know can hurt you, and is likely costing you money and increasing your security risks during an era of scarce resources. This white paper proposes six key strategies that enterprise security managers can use to improve their network defense posture.

Request Your Free Technology Downloads!
 
Rationalizing the Multi-Tool Environment
The rationalized multi-tool approach is flexible, scalable and cost effective. It provides the necessary input to the IT service management business processes. It preserves prior investments in monitoring tools, empowers technologists to select the best tools with which to do their jobs, and enhances effective response to incidents.

Request Your Free Technology Downloads!
 

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




© 2003-2010 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
For more Enterprise Application Development news, visit eWeek