itoa

#include <stdio.h>
#include <iostream>

using namespace std;

//整形
double myItoa(const char *pChar)
{
	//空指针
	if(pChar == NULL)
	{
		printf("NULL pointer\n");
		return 0;
	}
	
	int len = strlen(pChar);
	if( 0 == len )
	{
		//空字符串
		printf("NULL Char *\n");
		return 0;
	}
	else
	{
		int sign = 1;
		int i = 0;
		double result = 0.0;
		//正负号
		if(pChar[0] == '-')
		{
			if(pChar[1] == '.')
			{
				printf("invalid number (-.xxx)\n");
				return 0;
			}
			sign = -1;
			i++;
		}
		if(pChar[0] == '+')
		{
			if(pChar[1] == '.')
			{
				printf("invalid number (+.xxx)\n");
				return 0;
			}
			sign = 1;
			i++;
		}

		double base1 = 10;
		double base2 = 0.1;
		double basetmp = base1;
		for ( ;i < len; i++)
		{
			if(pChar[i] == '.')
			{
				double result1 = result;
				result = 0.0;
				if(basetmp == base2)
				{
					printf("invalid number (xxx.xx.xx)\n");
					return 0;
				}
				basetmp = base2;
				for (int j = strlen(pChar)-1; j > i; j--)
				{
					//cout<<pChar[j]<<endl;
					int diff = pChar[j]-'0';
					if(diff >= 10 || diff < 0)
					{
						//非法字符
						printf("pchar -  unvalid char: %c\n", pChar[j]);
						return 0;
					}
					result = (result+diff)*basetmp;
				}
				return sign*(result+result1);
			}
			int diff = pChar[i]-'0';
			if(diff >= 10 || diff < 0)
			{
				//非法字符
				printf("pchar -  unvalid char: %c\n", pChar[i]);
				return 0;
			}
			result = result*basetmp+diff;
		}
		return sign * result;
	}

	return 0;
}
void main()
{
	char* pc = new char[100];
	cin>>pc;
	//防止出界 2^64
	if(strlen(pc) > 20 ) 
	{
		printf("Big Number\n");
		return;
	}
	double pcI  = myItoa(pc);
	//cout<<sizeof(pcI)<<endl;
	printf("%lf\n",  pcI);
}



   

你可能感兴趣的:(c,null,include)