`
810364804
  • 浏览: 782193 次
文章分类
社区版块
存档分类
最新评论

剑指offer面试题(49)把字符串转换成整数

 
阅读更多
/*
 *name:jae chia
 *purpse:convert the string to interger
 *date:2014/6/21
 */

//功能测试(输入的字符串有正数,负数,和0)
//特殊输入测试(输入字符串为NULL指针,输入字符串为空字符串,输入的字符串中除第一位的'+','-'外,其余位还有其他字符
//
#include<iostream>
using namespace std;
#include<malloc.h>
#define MAX 10
enum Status {Valid=0,Invalid};
int now_status;//用于标识输入的字符串是有效还是无效;now_status=Valid 有效,now_status=Invalid 无效
int flag=1 ;//用于标识字符串所转换的整数的正负;正:flag=1,负:flag=-1;
int Str2Int(const char *string)
{
	
	const char *str=string;
	int num=0;
	now_status =Invalid;
    if(NULL!=str && '\0'!=*str)
	{
		if('+'==*str)
		{
			str++;
			flag=1;
		}
		else if('-'==*str)
		{
			str++;
			flag=-1;
		}
		if('\0'!=*str)
		{
			while(*str !='\0')
			{
				if(*str >='0' && *str<='9')
				{
					num=num*10+*str-'0';	  
					str++;
				}
				else
				{
					num=0;
					break;
				}
		    }
			if('\0'==*str)
			{
				now_status=Valid;
			}
	    }
    }
   return num;
}
int main(void)
{
	char *str=(char *)malloc(sizeof(char)*MAX);
	cout<<"input the string: ";
	cin>>str;
	int num=Str2Int(str);
	if(Invalid==now_status )
	{
		cout<<"The string you want to convert to a interger is invalid!"<<endl;
		return 0;
	}
	else
	{
		cout<<"The string you want to convert to a interger is valid and the interger is: ";
		if(-1==flag )
			cout<<-num<<endl;
		else
			cout<<num<<endl;    
	}
	return 0;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics