问题描述
我今天开始用C语言学习课程,但我不确定如何使用strtol
函数从命令行参数转换为整数字符串,而不是使用atoi
函数(对于由于某些原因,不允许使用atoi
函数。
如何更改以下代码以改为使用strtol
函数?如果可能,请说明您创建的变量(如果有)与strtol
函数相关的作用。
int main( int argc,char * argv[] ) {
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);
printf("num1 = %d,num2 = %d",num1,num2);
return 0;
}
解决方法
您可能知道的原型
long int strtol(const char *str,char **endptr,int base)
其中str
是原始字符串,而endptr
是指向之后的其余字符串的指针的地址。 base
是基础。
strtol()
找不到数字时返回0。确定它找到0时返回0,然后必须检查剩余数据并最终重新开始。
此
Original string: "2001 2002 2003 2004 0 2005"
2001 parsed string now: " 2002 2003 2004 0 2005"
2002 parsed string now: " 2003 2004 0 2005"
2003 parsed string now: " 2004 0 2005"
2004 parsed string now: " 0 2005"
0 was parsed: may be just the end of input
5 bytes remaining at the string: " 2005"
是下面的简短程序的输出,可以帮助您了解技巧
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char* argv[])
{
const char* pattern =
"2001 2002 2003 2004 0 2005";
char* input = (char*)pattern;
char* after = NULL;
long long int num1 = strtol(input,&after,10);
printf("Original string: \"%s\"\n\n",pattern);
do
{
printf("%8lld parsed\tstring now: \"%s\"\n",num1,after);
input = after;
num1 = strtol(input,10);
} while (num1 != 0);
printf("\n0 was parsed: may be just the end of input\n");
printf("\n%ud bytes remaining at the string: \"%s\"\n",strlen(after),after);
return 0;
};
// Compiled under MSVC 19.27
,
使用strtol将命令行中的数字转换为整数
[发现了许多 strtol()
个帖子,但对OP关于SO的问题并没有直接的C答案。]
strtol()
的良好用法涉及基础errno
和结束指针以及各种结果的测试。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc,char *argv[]) {
for (int a = 1; a < argc; a++) { // check command line arguments after argv[0].
int base = 10; // convert strings as encoded with decimal digits.
char *endptr; // location to store the end of conversion.
errno = 0;
long val = strtol(argv[a],&endptr,base);
printf("<%s> --> %ld:",argv[a],val);
if (argv[a] == endptr) {
printf(" No conversion.\n");
} else if (errno == ERANGE) { // ***
printf(" Out of `long` range.\n");
} else if (errno) {
printf(" Implementation specific error %d detected.\n",errno);
} else if (*endptr) {
printf(" Trailing junk <%s> after the numeric part.\n",endptr);
} else {
printf(" Success.\n");
}
}
}
***更好的代码在errno
之后立即使用strtol()
的值,以确保它反映出由于strtol()
而引起的错误,而不是稍后的功能。