4. 字符串和数字的互转
这节课我们来学习如何使用 C 语言的标准库函数实现字符串和数字的互转。
数字转字符串
数字转字符串可以使用 C 语言标准库函数 sprintf 来实现。 sprintf 是 C89 的标准库函数。
sprintf 函数的声明格式如下:
int sprintf(char *str, const char *format, ...);
sprintf 函数和 printf 函数是同系列的函数,同是在 stdio.h 文件中声明。只是 sprintf 是将格式化输出的内容放入一个字符型数组中并自动追加尾零 '\0'。 它的第二个参数 format 是格式化字符串,其中的 格式说明符(占位符)和 printf 函数的 格式说明符 完全一致。
以下是 sprintf 将数组转为字符串的示例
// filename: mysprintf.c
#include <stdio.h>
int main(int argc, char * argv[]) {
int x = 999;
float pi = 3.1415926;
char buf_x[100];
char buf_pi[100];
sprintf(buf_x, "%d", x); // buf_x 的内容为 "999"
sprintf(buf_pi, "%.3f", pi); // buf_pi 的内容为 " 3.142"
printf("%s\n%s\n", buf_x, buf_pi);
return 0;
}
运行结果如下:
weimingze@mzstudio:~$ gcc -o mysprintf mysprintf.c
weimingze@mzstudio:~$ ./mysprintf
999
3.142
字符串转数字
C 语言标准库中提供了如下四个常用于将 数字组成的字符串转为数字的函数
函数
说明
备注
int atoi(const char *nptr)字符串
nptr 转为整型数。C89 标准启用。
long atol(const char *nptr)字符串
nptr 转为长整型数。C89 标准启用。
long long atoll(const char *nptr)字符串
nptr 转为 long long 类型整数。C99 标准启用。
double atof(const char *nptr)字符串
nptr 转为双精度小数。C89 标准启用。
以上函数的在 stdlib.h 头文件中声明。
示例:
// filename: myatox.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
const char * pstr = "3.1415";
int value;
long int lvalue;
long long int llvalue;
double fvalue;
value = atoi(pstr);
lvalue = atol(pstr);
llvalue = atoll(pstr);
fvalue = atof(pstr);
printf("value: %d\n", value);
printf("lvalue: %ld\n", lvalue);
printf("llvalue: %lld\n", llvalue);
printf("fvalue: %f\n", fvalue);
return 0;
}
运行结果如下:
weimingze@mzstudio:~$ gcc -o myatox myatox.c
weimingze@mzstudio:~$ ./myatox
value: 3
lvalue: 3
llvalue: 3
fvalue: 3.141500
练习:
写程序,输入一个由整数数字组成的字符串,不使用标准库函数,自己编写代码将字符串转化为整数,然后将这个整数 加 1 后打印结果。