Shammer's Philosophy

My private adversaria

文字列が数値かどうか判定する

C には、isdigit という関数がある(ctype.h をインクルード)。これは、char の数値判定を行う関数。
しかし、一文字の数値判定は行えても文字列の数値判定を行える関数は見つけられなかったので自作。
簡単な内容だけれども・・・

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

int main(int argc, char *args[]){
    if( argc == 2 ){
	int len = strlen(args[1]);
	int i;
	int result = 1;
	for(i = 0; i < len && result ; i++){
	    result = isdigit(args[1][i]);
	}
	if( result ){
	    printf("%s is a number.\n", args[1]);
	}
	else {
	    printf("%s is not a number.\n", args[1]);
	}
    }
    else {
	printf("Usage: %s $1\n", args[0]);
    }
}

実行例は以下。

$ gcc isdigitsample.c 
$ 
$ 
$ ./a.out 555a a
Usage: ./a.out $1
$ ./a.out 
Usage: ./a.out $1
$ 
$ 
$ 
$ ./a.out 666
666 is a number.
$ ./a.out 6664957892
6664957892 is a number.
$ ./a.out 6664957892d351
6664957892d351 is not a number.
$