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

Member Avatar for iamthwee

store a char array = ["0123456789"]

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

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'.

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. :)

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!");
}
}

}

You for got a double quote in the first printf. :P
Change if ( input<0 || input>9) to if ( input<'0' || input>'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 != '\0').
Remember to increment i at the end of your loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.