check if string is number c
Checking if a String is a Number in C
To check if a string is a number in C, you can use the isdigit()
function to check each character of the string. Here are the steps to do this:
- Iterate Through the String: Loop through each character of the string.
- Check if Each Character is a Digit: Use the
isdigit()
function to check if each character is a digit. - Handle Decimal Point: If the string represents a floating-point number, handle the decimal point separately.
- Handle Negative Sign: If the string represents a negative number, handle the negative sign separately.
Here's a sample code snippet to demonstrate this:
#include <stdio.h>
#include <ctype.h>
int isNumber(const char* str) {
int i = 0;
int decimalPointCount = 0;
if (str[0] == '-' || str[0] == '+') {
i = 1;
}
for (; str[i] != '\0'; i++) {
if (!isdigit(str[i])) {
if (str[i] == '.' && decimalPointCount == 0) {
decimalPointCount++;
} else {
return 0;
}
}
}
return 1;
}
int main() {
const char* testString = "-123.45";
if (isNumber(testString)) {
printf("%s is a number.\n", testString);
} else {
printf("%s is not a number.\n", testString);
}
return 0;
}
In this code, the isNumber
function checks each character of the input string to determine if it represents a valid number. It handles negative numbers and floating-point numbers as well.