下列函数可以将字符串转换为数字:
函数名 作 用
atof() 将字符串转换为双精度浮点型值
atoi() 将字符串转换为整型值
atol() 将字符串转换为长整型值
strtod() 将字符串转换为双精度浮点型值,并报告不能被转换的所有剩余数字
strtol() 将字符串转换为长整值,并报告不能被转换的所有剩余数字
strtoul() 将字符串转换为无符号长整型值,并报告不能被转换的所有剩余数字
/* strtod example */
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* strtod */
int main ()
{
char szOrbits[] = "365.24 29.53";
char* pEnd;
double d1, d2;
d1 = strtod (szOrbits, &pEnd);
d2 = strtod (pEnd, NULL);
printf ("The moon completes %.2f orbits per Earth year.\n", d1/d2);
return 0;
}
/* strtol example */
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
int main ()
{
char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
char * pEnd;
long int li1, li2, li3, li4;
li1 = strtol (szNumbers,&pEnd,10);
li2 = strtol (pEnd,&pEnd,16);
li3 = strtol (pEnd,&pEnd,2);
li4 = strtol (pEnd,NULL,0);
printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);
return 0;
}
/* strtoul example */
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* strtoul */
int main ()
{
char buffer [256];
unsigned long ul;
printf ("Enter an unsigned number: ");
fgets (buffer, 256, stdin);
ul = strtoul (buffer, NULL, 0);
printf ("Value entered: %lu. Its double: %lu\n",ul,ul*2);
return 0;
}