// 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;
}
//
#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;
}