如何使用C中的strtol将命令行中的数字转换为inter



我今天开始了一门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;
}

使用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);
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");
}
printf("<%s> --> %ld:", argv[a], val);
}
}

您可能知道的原型是

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"nn", pattern);
do
{   
printf("%8lld parsedtstring now: "%s"n", num1, after);
input = after;
num1 = strtol(input, &after, 10);
} while (num1 != 0);
printf("n0 was parsed: may be just the end of inputn");
printf("n%ud bytes remaining at the string: "%s"n",
strlen(after), after);
return 0;
};
// Compiled under MSVC 19.27

最新更新