把字符串转化为数字
利用printf()和sprintf(), 通过各种转换说明, 可将数字从数值形式转换为字符串形式
char first[] = "Annie";
char last[] = "von wurstkasse";
double prize = 25000;
char ch[50];
sprintf(ch, "%s, %-19s: $%6.2f\n", last, first, prize);
atoi() 函数可用把字母数字转换为整数
/*hello.c -- 命令行参数转换为数字*/
#include <stdio.h>
#include <stdlib.h>//调用其中的atoi()函数
int main(int argc, char* argv[])
{
int i, times;
if (argc < 2 || (times = atoi(argv[1])) < 1)
printf("Usage: %s positive-number\n", argv[0]);
else
for (i = 0; i < times; i++)
puts("Hello, good looking!");
return 0;
}
若字符串仅以整数开头, 那么atoi()函数之转换开头部分的数字, 若命令行参数非数字, 该行为在c标准下是未定义的。
使用有错误检测功能的strtol()函数更加安全。
strto…系列函数
strtol()把字符串转换为long类型值, strtoul() 函数转换为unsigned long 类型, strtod()转换为double类型…
stdlib.h 该头文件包含了atoi(), atol(), atof()等函数的原型
/*调用strtol() 函数*/
#include <stdio.h>
#include <stdlib.h>
#define LIM 30
int main()
{
char number[LIM];
char* end;
long value;
puts("Enter a number (empty line to quit): ");
while (s_gets(number, LIM) && number[0] != '\0')
{
value = strtol(number, &end, 10);
printf("base 10 input, base 10 output: %ld, stopped at %s (%d)\n", value, end, *end);
value = strtol(number, &end, 16);
printf("base 16 input, base 10 output: %ld, stopped at %s (%d)\n", value, end, *end);
puts("Next number:");
}
puts("Bye!\n");
return 0;
}
strtol() 函数返回从字符串中转换出的数值, 第一个参数是源字符串, 第二个参数是转换停止时的地址, 第二个参数是源字符串中数值的进制。