C语言 字符串转换成int、long和double型

#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>

函数原型说明返回值
atoiint atoi(const char *nptr)将 nptr 指向的字符串转换为 int 型表示返回转换后的值。结果值不能用 int 型表示时的处理未定义
atollong atol(const char *nptr)将 nptr 指向的字符串转换为 long 型表示返回转换后的值。结果值不能用 long型表示时的处理未定义
atofdouble 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;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值