字符串转换为整数

/*
 * =====================================================================================
 *
 *       Filename:  StrtoI.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2014年02月28日 14时18分33秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Dr. Fritz Mehner (mn), mehner@fh-swf.de
 *        Company:  FH Südwestfalen, Iserlohn
 *
 * =====================================================================================
 */
#include<iostream>
#include<cstring>
using namespace std;

class StrtoInt
{
	public:
		StrtoInt(const char *st):mark(false),positive(-1),minus(-1){
			s = new char[strlen(st)+1];
			strncpy(s,st,strlen(st));
		}
		int getnum();
		
		bool mark;//标记是否转换有效。可以判断数字0是否是返回的正确结果或者错误信息
	private:
		//char *s;
		int strtoi();
		int positive;//标记正号
		int minus;//标记负号
		char *s;
};
int StrtoInt::strtoi()
{
	int length = strlen(s);
	int sum = 0;
	if(NULL == s)
		return 0;
	if(('+'==*s||'-'==*s)&&1==strlen(s))
		return 0;
	if('+' == *s&&strlen(s)>1)
		positive = 1;
	if('-' == *s&&strlen(s)>1)
		minus = 2;
	if('+' == *s || '-'== *s)
	for(int i = 1; i < length;i++)
	{
		if(s[i] >= '0' && s[i] <= '9')
		{
			sum = sum*10+(s[i] - '0');//累加
		}
		else 
			return 0;
		mark = true;//把标记位设置为真。
	}
	else
	{
		for(int i = 0; i < length; i++)
		{
			if(s[i] >= '0' && s[i] <= '9')
			{
				sum = sum*10+(s[i] - '0');
			}else return 0;

		}
		mark = true;
	}
    return sum;
}
int StrtoInt::getnum()
{
	int num = strtoi();
	if(num == 0 && mark == true)
		return 0;
	if(positive == 1)
		return num;
	if(minus == 2)
		return (0-num);
	return num;
}
int main()
{
	StrtoInt ch("123");
	StrtoInt ch1("-123");
	StrtoInt ch2("f23");
	cout << ch.getnum() << endl;
	cout << ch1.getnum()<<endl;
	cout << ch2.getnum() << endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值