-3

我正在使用atof(word),其中 word 是一种char类型。它在单词是数字时起作用,例如 3 或 2,但 atof 不区分单词何时是运算符,例如"+". 有没有更好的方法来检查字符是否是数字?

我是CS的新手,所以我对如何正确地做到这一点感到很困惑。

4

4 回答 4

4

如果您正在检查单个char,请使用该isdigit功能。

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

输出:

2 is digit: yes
+ is digit: no
a is digit: no
于 2016-02-12T20:26:06.950 回答
4

是的,有,strtol()。例子

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

以上将打印"xaxax' are not numbers"`。

这个想法是这个函数在找到任何非数字字符时停止,并endptr指向原始指针中非数字字符出现的位置。这不会将“运算符”视为非数值,因为符号用作数字的符号,因此"+10"可以转换为10,如果要解析两个操作数之间的“运算符”,则需要一个解析器,一个简单的可以写使用strpbrk(input, "+-*/"),阅读手册strpbrk()

于 2016-02-12T20:26:38.053 回答
2

你的意思是如果一个字符串只包含数字?

#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;
}
于 2016-02-12T20:30:36.010 回答
1

假设按单词,您的意思是一个字符串,在 C 中,它是 char* 或 char[]。

我个人会使用atoi()

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

例子:

#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;
}

输出:

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

但是,如果您只是检查单个字符,则只需使用 isdigit()

于 2016-02-13T09:08:00.480 回答