#include <stdlib.h>
int atoi( const char *str );
将字符串 str 转换成一个整数并返回结果。参数 str 以数字开头,当函数从 str 中读到非数字字符则结束转换并将结果返回。
(1)待转换的字符串是一个合法的数字字符串。如下:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int n;
char *str = "12345.67";
n = atoi(str);
printf("string = %s integer = %d\n", str, n);
return 0;
}输出结果:
string = 12345.67 integer = 12345
(2)待转换字符串前缀是一个合法字符串,尾部是一个非数字字符串。如下:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int n;
char *str = "12345.67hello world";
n = atoi(str);
printf("string = %s integer = %d\n", str, n);
return 0;
}输出结果:
string = 12345.67hello world integer = 12345