当使用atoi和strtol函数将字符串转换为整数时,需要注意一些陷阱。这些函数的错误行为可能会导致程序崩溃、数据损坏或安全漏洞。以下是一些常见的问题和解决方案:
char str[20] = "2147483648";
errno = 0;
long num = strtol(str, NULL, 10);
if (num == LONG_MAX && errno == ERANGE) {
// 处理错误
}
char str[20] = "123abc";
int num;
if (sscanf(str, "%d", &num) == 1) {
// 转换成功
} else {
// 处理错误
}
char str[20] = "12345678901234567890";
char buf[20];
strncpy(buf, str, sizeof(buf));
buf[sizeof(buf) - 1] = '\0'; // 确保缓冲区以NULL结尾
int num = atoi(buf);
上一篇:Atoi函数无法正确转换字母。