在大学时,我被问到我们的程序是否检测到从命令行参数输入的字符串是否是一个它没有的整数(./Program 3.7
)。现在我想知道我怎么能发现这个。因此,例如a
的输入无效,其中atoi检测到,但是例如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。希望我的问题很明确。非常感谢。
答案 0 :(得分:10)
查看strtol。
如果endptr不为NULL,则strtol()将第一个无效字符的地址存储在* endptr中。但是,如果根本没有数字,则strtol()将str的原始值存储在* endptr中。 (因此,如果返回时* str不是
\0' but **endptr is
\ 0',则整个字符串都有效。)
#include <stdio.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");
}
}
答案 1 :(得分: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.
答案 2 :(得分: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:只是为了好玩 - 它现在应该解析数字
答案 3 :(得分:1)