字符串转换为整型

将一个整数字符串转换为整型,考虑了非数字字符,正负号以及溢出的情况。

</pre><pre code_snippet_id="404909" snippet_file_name="blog_20140624_3_1248501" name="code" class="cpp">#include <stdio.h>
#include <assert.h>
#include <ctype.h>
#include <math.h>

int StrToInt(char* string)
{
	unsigned int number=0;
	assert(string);

	if(*string=='-'){
		++string;
	}
	while(*string!=0){
		if(!isdigit(*string))
			return -1;
		number=number*10+*string-'0';
		string++;
	}

	return number;
}

int main()
{
	char* m_str="-1347483600";
	unsigned int m_num;
	int flag;
	int m_num1;

	if(*m_str=='-')
		flag=1;
    m_num=StrToInt(m_str);
	if(flag==1){
		if(m_num>(pow(2,31)-1)){
			printf("overflow!,error number:-3\n");
			return -3;
		}
		m_num1=m_num;
		m_num1=-m_num1;
		printf("%d\n",m_num1);
	}
	else
		printf("%u\n",m_num);

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值