在C语言中,将字符串转换为数字可以使用标准库函数,这些函数通常定义在 <stdlib.h> 头文件中,以下是几种常见的转换方法:

(图片来源网络,侵删)
字符串转整数(int)
使用 atoi() 函数:
#include <stdio.h>
#include <stdlib.h>
int main() {
const char *str = "12345";
int num = atoi(str);
printf("转换为整数: %d\n", num); // 输出: 12345
return 0;
}
- 特点:
- 遇到非数字字符时停止转换(如
"123abc"会转为123)。 - 无法检测转换错误,返回
0时可能表示转换失败或原字符串为"0"。
- 遇到非数字字符时停止转换(如
字符串转长整型(long)
使用 atol() 或 atoll()(C99):
#include <stdio.h>
#include <stdlib.h>
int main() {
const char *str = "9876543210";
long num = atol(str);
printf("转换为长整型: %ld\n", num); // 输出: 9876543210
return 0;
}
- 特点:
- 类似
atoi(),但支持更大的数值范围。
- 类似
字符串转浮点数(float/double)
使用 atof() 函数:
#include <stdio.h>
#include <stdlib.h>
int main() {
const char *str = "3.14159";
double num = atof(str);
printf("转换为浮点数: %f\n", num); // 输出: 3.141590
return 0;
}
- 特点:
- 支持科学计数法(如
"1.23e4"转为0)。 - 同样无法检测错误。
- 支持科学计数法(如
更安全的转换(推荐)
使用 strtol()、strtoll()、strtod() 等函数,它们可以检测转换错误:

(图片来源网络,侵删)
示例:strtol() 转换为 long
#include <stdio.h>
#include <stdlib.h>
#include <errno.h> // 用于错误检测
int main() {
const char *str = "12345abc";
char *endptr; // 存储转换停止的位置
long num;
errno = 0; // 重置错误标志
num = strtol(str, &endptr, 10); // 10表示十进制
if (errno == ERANGE) {
printf("数值超出范围!\n");
} else if (endptr == str) {
printf("未进行任何转换!\n");
} else {
printf("转换结果: %ld\n", num); // 输出: 12345
printf("剩余字符: %s\n", endptr); // 输出: "abc"
}
return 0;
}
- 参数说明:
str:待转换的字符串。endptr:指向转换停止位置的指针(可选)。base:进制(如10为十进制,16为十六进制)。
示例:strtod() 转换为 double
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main() {
const char *str = "3.14e-2";
char *endptr;
double num;
num = strtod(str, &endptr);
if (errno == ERANGE) {
printf("数值超出范围!\n");
} else if (endptr == str) {
printf("未进行任何转换!\n");
} else {
printf("转换结果: %f\n", num); // 输出: 0.031400
}
return 0;
}
处理十六进制/八进制
通过指定 base 参数:
#include <stdio.h>
#include <stdlib.h>
int main() {
const char *hex_str = "1A3F"; // 十六进制
const char *oct_str = "755"; // 八进制
long num1 = strtol(hex_str, NULL, 16);
long num2 = strtol(oct_str, NULL, 8);
printf("十六进制 %s 转为十进制: %ld\n", hex_str, num1); // 输出: 6719
printf("八进制 %s 转为十进制: %ld\n", oct_str, num2); // 输出: 493
return 0;
}
注意事项
- 错误处理:
atoi()/atof()无法区分转换失败和原值为0。- 推荐使用
strtol()/strtod()并检查errno和endptr。
- 溢出:
- 如果数值超出目标类型的范围,
strtol()会设置errno = ERANGE。
- 如果数值超出目标类型的范围,
- 前导/后缀空格:
- 标准库函数不会自动跳过字符串前后的空格,需手动处理(如用
strtrim())。
- 标准库函数不会自动跳过字符串前后的空格,需手动处理(如用
| 函数 | 目标类型 | 是否检测错误 | 进制支持 |
|---|---|---|---|
atoi() |
int |
否 | 仅十进制 |
atol() |
long |
否 | 仅十进制 |
atof() |
double |
否 | 浮点数 |
strtol() |
long |
是 | 自定义 |
strtoll() |
long long |
是 | 自定义 |
strtod() |
double |
是 | 浮点数 |
根据需求选择合适的函数,优先使用带错误检测的版本(如 strtol())。

(图片来源网络,侵删)
