954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how do i figure out if a string has a number in it?

hey guys how would i figure out if a string has a number in it without using any aditional libraries?

revenge2
Junior Poster in Training
79 posts since Feb 2007
Reputation Points: 10
Solved Threads: 2
 

store a char array = ["0123456789"]

Loop through said string to check if it contains any of those numbers. Boom job done.

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

store a char array = ["0123456789"]

Loop through said string to check if it contains any of those numbers. Boom job done.


Or loop through the string and check if any char is between the acsii value's of '0' and '9'.

Hiroshe
Posting Whiz in Training
256 posts since Jun 2008
Reputation Points: 431
Solved Threads: 17
 
Or loop through the string and check if any char is between the acsii value's of '0' and '9'.


Or just compare against '0' and '9' because the values have to be contiguous and using the underlying values means your code is tied to ASCII and any other character sets that correspond directly to ASCII for the decimal digits:

int isDigit = (c >= '0' && c <= '9');

Do not write unportable code if the portable version is easier to read, write, and maintain. :)

Tom Gunn
Master Poster
733 posts since Jun 2009
Reputation Points: 1,446
Solved Threads: 135
 

ah thanks alot. My question was wrong ealier i was actually trying to fingure out if there were any characters in a character string. (the input is binary or decimal number). i wanted to check whether it contained any characters so that i could print out "invalid number" .

would this be correct for the above situation?

#include <stdio.h>

int main() {
char input[80];
printf("number: );
gets(input);

int i=0;
while (i != '\0') {
if ( input[i]<0 || input[i]>9) {
printf("invalid number!");
}
}

}
revenge2
Junior Poster in Training
79 posts since Feb 2007
Reputation Points: 10
Solved Threads: 2
 

You for got a double quote in the first printf. :P
Change if ( input[i]<0 || input[i]>9) to if ( input[i]<'0' || input[i]>'9'). '9' is different than 9.
Use fgets() instead of gets(). It's safer.
Add a return 0; at the end of your main().
Change while (i != '\0') to while (input[i] != '\0').
Remember to increment i at the end of your loop.

Hiroshe
Posting Whiz in Training
256 posts since Jun 2008
Reputation Points: 431
Solved Threads: 17
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You