-1

I'm using atof(word), where word is a char type. It works when the word is a number, such as 3 or 2, but atof doesn't distinguish when word is an operator, such as "+". Is there a better way to check whether the char is a number?

I'm a newbie to CS, so I'm quite confused on how to do this properly.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
agupta2450
  • 29
  • 1
  • 1
  • 1

4 Answers4

5

If you're checking a single char, use the isdigit function.

#include <stdio.h>
#include <ctype.h>

int main()
{
    printf("2 is digit: %s\n", isdigit('2') ? "yes" : "no");
    printf("+ is digit: %s\n", isdigit('+') ? "yes" : "no");
    printf("a is digit: %s\n", isdigit('a') ? "yes" : "no");
}

Output:

2 is digit: yes
+ is digit: no
a is digit: no
dbush
  • 205,898
  • 23
  • 218
  • 273
4

Yes there is, strtol(). Example

char *endptr;
const char *input = "32xaxax";
int value = strtol(input, &endptr, 10);
if (*endptr != '\0')
    fprintf(stderr, "`%s' are not numbers\n");

The above would print "xaxax' are not numbers"`.

The idea is that this function stops when it finds any non numeric character, and makes endptr point to the place where the non numeric character appeared in the original pointer. This will not consider and "operator" as a non numeric value because "+10" is convertible to 10 since the sign is used as the sign of the number, if you want to parse the "operator" between two operands you need a parser, a simple one could be written using strpbrk(input, "+-*/"), read the manual for strpbrk().

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
2

Do you mean if a string contains only digits?

#include <stdio.h>
#include <ctype.h>

int main(void)
{
    char *str = "241";
    char *ptr = str;

    while (isdigit(*ptr)) ptr++;
    printf("str is %s number\n", (ptr > str) && (*str == 0) ? "a" : "not a");
    return 0;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
1

Assuming by word, you mean a string, which in C, is either a char* or a char[].

Personally I would use atoi()

This function returns the converted integral number as an int value. If no valid conversion could be performed, it returns zero.

Example:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void is_number(char*);

int main(void) {
    char* test1 = "12";
    char* test2 = "I'm not a number";

    is_number(test1);
    is_number(test2);
    return 0;
}

void is_number(char* input){
    if (atoi(input)!=0){
        printf("%s: is a number\n", input);
    }
    else
    {
        printf("%s: is not a number\n", input);
    }
    return;
}

Output:

12: is a number
I'm not a number: is not a number

However if you're just checking a single character, then just use isdigit()

JJGong
  • 129
  • 2
  • 11