|
发表于 2023-4-2 22:22:05
|
显示全部楼层
本楼为最佳答案
在使用 strtol() 函数将字符串转换为长整型时,函数会返回转换后的长整型值,并且将指向字符串中第一个无法转换的字符的指针存储在 end 指针中。
在你的代码中, word2 字符串中第一个无法转换为数字的字符是 a,因此 end 指针应该指向该字符。然而,你的代码的输出结果显示 end 指针为 NULL。
这可能是因为 strtol() 函数在遇到字符串中第一个无法转换的字符时,会停止转换并将 end 指针设置为 NULL。在这种情况下,你可以通过检查 errno 变量是否被设置为 EINVAL 来确定转换是否成功,如果转换失败,errno 将被设置为 EINVAL。
因此,你可以修改你的代码以检查 errno 变量来确定转换是否成功,如下所示:
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- int main(void)
- {
- char word1[] = "***";
- char word2[] = "101aaa";
- char word3[] = "***";
- char *end;
- long int val;
- errno = 0; // 初始化 errno 变量
- val = strtol(word2, &end, 10); // 调用 strtol() 函数
- if (errno == EINVAL) { // 如果转换失败,输出错误信息
- printf("Error: Invalid argument\n");
- } else { // 否则输出转换后的值和 end 指针指向的字符
- printf("word: %ld\n", val);
- if (end != NULL) {
- printf("%s\n", end);
- } else {
- printf("(null)\n");
- }
- }
- return 0;
- }
复制代码
这样,如果转换成功,输出结果将为:
如果转换失败,输出结果将为:
|
|