2016-02-12 110 views
-3

我使用的是atof(word),其中word是char类型。它适用于单词是数字的情况,比如3或2,但atof不区分单词是否是操作符,如"+"。有没有更好的方法来检查char是否是一个数字?如何检查char是否是c中的数字?

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

+0

'atof()'不采用'char'类型,它需要一个'char'指针指向一个字符串,即一个* null *字节结尾的序列。 –

+0

你正在检查像'7'一样的'char'还是像''1234''这样的字符串? – chux

+0

我有一个文本文件,里面有数字,他们可能是单个或多个数字,我正在一个一个地阅读单词,并检查单词是否是数字 – agupta2450

回答

2

如果您正在检查单个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 
+0

你真的得到了[2是数字: 1](http://ideone.com/I2uHfQ)? – Michi

+0

@Michi重写了输出以使其更清晰。 – dbush

1

是有,strtol()。例如

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

以上将打印" xaxax”不是数字“`。

的想法是,这个功能时,它发现任何非数字字符停止,使得endptr点的地方,其中非数字字符出现在原始指针中,因为"+10"可以转换为10,所以不会将“运算符”视为非数值,因为如果要解析“”运算符,该符号将用作数字的符号两个之间的“”您需要解析器的操作数,可以使用strpbrk(input, "+-*/")编写一个简单的解析器,请阅读strpbrk()的手册。

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

假设是字,你的意思是一个字符串,它在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( )

相关问题