检查命令行输入是否有效整数(C)

时间:2015-02-12 03:03:39

标签: c string char integer command-line-arguments

我试图验证我的程序用户是否在命令行中输入了有效的整数。我遇到了一个问题:拒绝所有输入。

这是我拥有的

// Make sure input is a valid int
char *ptr = NULL;
long int input = strtol(argv[i+1], &ptr, 10);
if(ptr == NULL){
    userMinInt = input;
    minIntSet = true;    
}
else
    fprintf(stderr, "You must enter a valid integer for <min-int>. Using default value of %ld\n", minInt);

2 个答案:

答案 0 :(得分:1)

代码正在检查结束指针是否为NULL。相反,代码应检查:

1)结束指针是否指向空字符'\0'
2)结束指针是否与开始不同?

下面的其他检查:

char *start = argv[i+1];  // maybe should be argv[i]
char *ptr;
// set errno to 0 for subsequent check
errno = 0;
long int input = strtol(start, &ptr, 10);
if (ptr == start) {
  fprintf(stderr, "No conversion done.\n");
}
else if (*ptr != 0) {
  fprintf(stderr, "Extra data after the number.\n");
}
else if (errno) {
  fprintf(stderr, "Number outside long range.\n");
}
else if (input < INT_MIN || input > INT_MAX) {
  fprintf(stderr, "Number %ld outside int range.\n", input);
}
else {
  printf("Number is %d.\n", (int) input);
}

答案 1 :(得分:0)

感谢彼得,我已经解决了这个问题。这是新的工作代码:

// Make sure input is a valid int
char *ptr = NULL;
long int input = strtol(argv[i+1], &ptr, 10);
if(ptr != NULL && *ptr == (char)0){
    userMinInt = input;
    minIntSet = true;
}
else
    fprintf(stderr, "You must enter a valid integer for <min-int>. Using default value of %ld\n", minInt);