c 实现: 将字符串转换为整数,不准用库函数

// TestWin32Consle.cpp : 定义控制台应用程序的入口点。
//


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


using namespace std;


void testFormat(const char* szStr);
int strToInt(const char* szStr, int* iResult);


int _tmain(int argc, _TCHAR* argv[])
{
testFormat("123456789");


testFormat("987654321");


testFormat("+123456");


testFormat("-654321");


testFormat("-abcd");


testFormat("-123c");


printf("\n");
system("pause");
return 0;
}


void testFormat(const char* szStr)
{
int ret = 0;
if(strToInt(szStr,&ret) == 0)
{
printf("\nstrToInt result successed: \"%s\" --> %d\n",szStr,ret);
}
else
{
printf("\nstrToInt failed : the string \"%s\" can not format to intger !!!\n",szStr);
}
}




/*
format the string to intger
return 0 is success, -1 is fail
*/
int strToInt(const char* szStr, int* iResult)
{
int iRet = -1; //返回值,0 成功,-1失败
if(szStr == NULL)
goto RETURN;


int isAdd = 1;
const char* str = szStr;
//判断第一个字符,如"123" ,"+123","-123"是否为负数
if(*str == '-')
{
isAdd = -1;
str++;

else if(*str == '+')
{
str++;
}
while (*str != '\0')
{
//is number?
if(*str >= '0' && *str <= '9')
{
*iResult = (*iResult) * 10 + (*str - '0');
}
else
{
goto RETURN;
}


str++;
}
iRet = 0; //0 表示成功
*iResult = (*iResult) * isAdd; //
//printf("\nstring To int successed!  \"%s\" --> %d\n",szStr,iResult);


RETURN:
return iRet;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值