#include <stdio.h>
#include <stdlib.h>
#define LENGTH 128
int main(void){
char str[LENGTH];
puts("请输入字符串:");
scanf("%s", str);
printf("转换为int型后为 %d。\n", atoi(str));
printf("转换为long型后为 %ld。\n", atol(str));
printf("转换为double型后为 %lf。\n", atof(str));
return 0;
}
运行结果:
使用函数库:#include <stdlib.h>
函数 | 原型 | 说明 | 返回值 |
---|---|---|---|
atoi | int atoi(const char *nptr) | 将 nptr 指向的字符串转换为 int 型表示 | 返回转换后的值。结果值不能用 int 型表示时的处理未定义 |
atol | long atol(const char *nptr) | 将 nptr 指向的字符串转换为 long 型表示 | 返回转换后的值。结果值不能用 long型表示时的处理未定义 |
atof | double atof(const char *nptr) | 将 nptr 指向的字符串转换为 double 型表示 | 返回转换后的值。结果值不能用 double 型表示时的处理未定义 |
atoi 函数实现:
int atoi(const char *nptr){
int flag = 1;
int result = 0;
if(nptr == NULL)
return 0;
while(*nptr == ' ' || *nptr == '\t')
nptr++;
if(*nptr == '-'){
flag = -1;
nptr++;
}
while(*nptr != '\0'){
if(*nptr >= 0 && *nptr <= '9'){
result = result*10 + (*nptr - '0');
} else {
break;
}
nptr++;
}
return result * flag;
}
atol 函数实现:
int atol(const char *nptr){
int flag = 1;
long result = 0;
if(nptr == NULL)
return 0;
while(*nptr == ' ' || *nptr == '\t')
nptr++;
if(*nptr == '-'){
flag = -1;
nptr++;
}
while(*nptr != '\0'){
if(*nptr >= 0 && *nptr <= '9'){
result = result*10 + (*nptr - '0');
} else {
break;
}
nptr++;
}
return result * flag;
}
atof 函数实现:
#include <stdio.h>
#define LENGTH 128
typedef enum{false,true} bool;
double atof(const char* nptr){
double result = 0.0;
double d = 10.0;
int count = 0;
if(nptr == NULL){
return 0;
}
while(*nptr == ' ' || *nptr == '\t'){
nptr++;
}
bool flag = false;
while(*nptr == '-'){
flag = true;
nptr++;
}
if(!(*nptr >= '0' && *nptr <= '9')){
return result;
}
while(*nptr >= '0' && *nptr <= '9'){
result = result * 10 + (*nptr - '0');
nptr++;
}
if(*nptr == '.'){
nptr++;
}
while(*nptr >= '0' && *nptr <= '9'){
result = result + (*nptr - '0') / d;
d *= 10.0;
nptr++;
}
result = result * (flag ? -1.0 : 1.0);
if(*nptr == 'e' || *nptr == 'E'){
flag = (*++nptr == '-') ? true : false;
if(*nptr == '+' || *nptr == '-'){
nptr++;
}
while(*nptr >= '0' && *nptr <= '9'){
count = count*10 + (*nptr - '0');
nptr++;
}
if(flag == true) {
while(count > 0){
result = result / 10;
count--;
}
}
if(flag == false){
while(count > 0){
result = result * 10;
count--;
}
}
}
return result;
}
int main(void){
char str[LENGTH];
puts("请输入字符串:");
scanf("%s", str);
printf("转换为double型后为 %f。\n", atof(str));
return 0;
}