引数文字列変換改良版
引数を文字列にする実装として、引数の文字列を数値に変換する - Shammerismというのを書いてみたけれども、この実装だと数値以外が渡されても0として扱っていたので、文字列が数値かどうか判定する - Shammerismの実装を利用して書きなおした。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int checknumber(char *v){ int len = strlen(v); int i; int result = 1; for(i = 0; i < len && result ; i++){ result = isdigit(v[i]); } return result; } int main(int argc, char *args[]){ if( argc == 2 ){ if( checknumber(args[1]) ){ int x = atoi(args[1]); printf("Command line argument value is %d, this is number.\n", x); } else { printf("Command line argument %s is not number\n", args[1]); } } else { printf("Usage: %s $Number\n", args[0]); } return 0; }
これだと、数値以外はエラー判定してくれる。実行例は以下。
$ gcc cliargument-v2.c $ $ $ $ ./a.out 66698xxx Command line argument 66698xxx is not number $ $ $ ./a.out 1234567890 Command line argument value is 1234567890, this is number. $ $