需包含头文件:C 标准库 - <stdlib.h>
文章目录
描述声明参数返回值实例在windows VS上测试1206 用atoi转换long,发现溢出了描述
C 库函数int atoi(const char *str)
把参数 str 所指向的字符串转换为一个整数(类型为 int 型)。
声明
下面是 atoi() 函数的声明。
int atoi(const char *str)
参数
str – 要转换为整数的字符串。返回值
该函数返回转换后的长整数,如果没有执行有效的转换,则返回零。
实例
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(){int val;char str[20];strcpy(str, "98993489");val = atoi(str);printf("字符串值 = %s, 整型值 = %d\n", str, val);strcpy(str, "");val = atoi(str);printf("字符串值 = %s, 整型值 = %d\n", str, val);return(0);}
让我们编译并运行上面的程序,这将产生以下结果:
字符串值 = 98993489, 整型值 = 98993489字符串值 = , 整型值 = 0
在windows VS上测试
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(){int val;char str[20];strcpy_s(str, "98993489");val = atoi(str);printf("字符串值 = %s, 整型值 = %d\n", str, val);strcpy_s(str, "");val = atoi(str);printf("字符串值 = %s, 整型值 = %d\n", str, val);strcpy_s(str, "0");val = atoi(str);printf("字符串值 = %s, 整型值 = %d\n", str, val);return(0);}
字符串值 = 98993489, 整型值 = 98993489字符串值 = , 整型值 = 0字符串值 = 0, 整型值 = 0
参考文章:C 库函数 - atoi()
1206 用atoi转换long,发现溢出了
可以用atol嘛,,,,
在linux ubuntu虚拟机上:
#include <time.h> #include <stdio.h>#include <stdlib.h>#include <string.h>int main(){long msec = 0;char str[20] = "1638793844090";for (size_t i = 0; i < strlen(str); i++) {msec = msec * 10 + (str[i] - '0');}printf("%ld\n", msec);printf("%ld\n", atol(str));return(0);}
运行结果:
16387938440901638793844090