2016-02-12 107 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( )

相關問題