atoi函数

做题的时候碰到了这个,要求把字符串里的字符数字转换为数字输出出来,而且要对8进制和16进制的输入进行处理,

我们假设输入都是正规的数,即:

十进制不是以0开头的,

八进制是以前缀0开头的,

十六进制是以前缀0x或0X开头的;

下面贴上代码:

#include <iostream>
#include <cctype>
#include <cstdlib>
#include <cmath>

using namespace std;

int My_atoi(char * str)
{
	int number = 0;
	int sig = 1;
	
	
	if(*str == '-')
	{
		sig = -1;
		++str;
	}
	char * s1,* s2;
	s1 = s2 = str;	
	if(*s1 != '0')
	{
		cout << "检测到输入为十进制数:\n";
		while(*str != '\0')
			number = number * 10 + *str++ - '0';
	}
	if(*s1 == '0' && *(++s1) != 'x' && *s1 != 'X')
	{
		cout << "检测到输入为八进制数:\n"; 
		while(*s1 != '\0')
			number = number * 8 + *s1++ - '0';
	}
	if(*s2 == '0' && (*(++s2) == 'x' || *s2 == 'X'))
	{
		cout << "检测到输入为16进制数:\n";
		char *pc1, *pc2;
		pc1 = pc2 = ++s2;
		
		while(*pc1 != '\0')
		{
			if(isdigit(*pc1))
			{
				number = number * 16 + *pc1 - '0';
			}
			if(isalpha(*pc1))
			{
				number = number * 16 + *pc1 - '0' - 39;
			}
			++pc1;
		}
	} 
			
	return number * sig;
}
int main()
{
	char a[30];	
	cout << "Enter your string value\n";
	while(cin.getline(a, 30))
	{
		int x = My_atoi(a);
		cout << "The number in the string is " << x << endl; 
		cout << "Enter next string values: \n";
	}
	
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值