4

在大学时,有人问我我们的程序是否检测到从命令行参数输入的字符串是否是整数,而它没有检测到(./Program 3.7)。现在我想知道如何检测到这一点。因此,例如aatoi 检测到的输入无效,但例如输入3.6应该是无效的,但 atoi 会将其转换为整数。

#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc > 1) {
        int number = atoi(argv[1]);
        printf("okay\n");
    }
}

但是只有当 argv[1] 真的是一个整数时才应该打印 offcourse OK。希望我的问题很清楚。非常感谢。

4

4 回答 4

11

看看strtol

如果 endptr 不为 NULL,strtol() 将第一个无效字符的地址存储在 *endptr 中。但是,如果根本没有数字,strtol() 将 str 的原始值存储在 *endptr 中。(因此,如果 *str 在返回时不是\0' but **endptr is \0',则整个字符串都是有效的。)

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
  if (argc > 1) {
    char* end;
    long number = strtol(argv[1], &end, 0);
    if (*end == '\0')
      printf("okay\n");
  }
}
于 2010-01-08T00:15:32.367 回答
2

假设您想知道如何在代码中完成它(如果它确实是家庭作业,则可能),一种方法是根据字符串考虑什么构成整数。它很可能是:

  • 可选符号,+/-。
  • 一个必需的数字。
  • 任意数量的可选数字(但要注意溢出)。
  • 字符串的结尾。

根据该规范,您可以编写一个为您完成工作的函数。

像这样的伪代码将是一个好的开始:

set sign to +1.
set gotdigit to false.
set accumulator to 0.
set index to 0.
if char[index] is '+':
    set index to index + 1.
else:
    if char[index] is '-':
        set sign to -1.
        set index to index + 1.
while char[index] not end-of-string:
    if char[index] not numeric:
        return error.
    set accumulator to accumulator * 10 + numeric value of char[index].
    catch overflow here and return error.
    set index to index + 1.
    set gotdigit to true.
if not gotdigit:
    return error.
return sign * accumulator.
于 2010-01-08T00:16:18.387 回答
1
int okay = argc>1 && *argv[1];
char* p = argv[1];
int sign = 1;
int value = 0;
if( *p=='-' ) p++, sign=-1;
else if( *p=='+' ) p++;
for( ; *p; p++ ) {
    if( *p>='0' && *p<='9' ) {
        value = 10*value + *p-'0';
    } else {
        okay = 0;
        break;
    }
}
if( okay ) {
    value *= sign;
    printf( "okay, value=%d\n", value );
}

编辑:允许 - 和 + 字符

你甚至可以把它压缩成一个密集的单层或两层。或者您可能会找到具有相同功能的库函数;)

EDIT2:只是为了好玩-它现在应该解析数字

于 2010-01-08T00:17:48.693 回答
1

所以你最好的选择是strtof() http://publib.boulder.ibm.com/infocenter/zos/v1r10/topic/com.ibm.zos.r10.bpxbd00/strtof.htm

于 2010-01-08T00:23:05.627 回答