C 语言 convert 函数:从字符串到数字的转换358


在 C 语言中,convert 函数是一个库函数,用于将字符串表示的数字转换为其相应的整数或浮点数。该函数在标准库 中声明,可用于将字符串表示的数字转换为各种基本数据类型,如 int、long 和 double。

原型

convert 函数的原型如下:```c
#include
char *strtol(const char *str, char endptr, int base);
char *strtod(const char *str, char endptr);
```

str:要转换的字符串。
endptr:指向字符串中第一个无法转换字符的指针。如果成功转换整个字符串,则 endptr 为 NULL。
base:要使用的转换基数(对于 strtol)。基数必须在 0 到 36 之间,0 表示自动检测基数。

strtol 函数

strtol 函数将字符串表示的数字转换成长整数 (long)。它将字符串作为第一个参数,并返回转换后的数字。

如果转换失败,则 strtol 返回 0 并将 errno 设置为 EINVAL。

strtod 函数

strtod 函数将字符串表示的数字转换成双精度浮点数 (double)。它将字符串作为第一个参数,并返回转换后的数字。

如果转换失败,则 strtod 返回 0 并将 errno 设置为 EINVAL。

示例

以下示例展示了如何使用 strtol 函数将字符串表示的数字转换为长整数:```c
#include
int main() {
char str[] = "123";
char *endptr;
long num = strtol(str, &endptr, 0);
if (endptr == str) {
// 转换失败
printf("无法转换字符串。");
} else {
// 成功转换
printf("转换后的数字为:%ld", num);
}
return 0;
}
```

该代码打印以下输出:```
转换后的数字为:123
```

以下示例展示了如何使用 strtod 函数将字符串表示的数字转换为双精度浮点数:```c
#include
int main() {
char str[] = "3.14";
char *endptr;
double num = strtod(str, &endptr);
if (endptr == str) {
// 转换失败
printf("无法转换字符串。");
} else {
// 成功转换
printf("转换后的数字为:%lf", num);
}
return 0;
}
```

该代码打印以下输出:```
转换后的数字为:3.140000
```

注意事项

使用 convert 函数时需要注意以下几点:* 字符串必须包含有效的数字。
* 基数(仅适用于 strtol)必须在 0 到 36 之间。
* 转换后的数字可能超出目标数据类型的范围。
* 如果转换失败,convert 函数将返回 0 并设置 errno。

2024-11-27


上一篇:c语言自定义实现power函数

下一篇:使用 C 语言输出 19 位数字的完整指南