注意的问题是:正负号;是否越界,也即是否全是数字;参数判断,一定要保证合法,不合法的中断运行
#include "stdafx.h"
#include <iostream>
#include <assert.h>
using namespace std;
int atoi2(char *str);
int main(void)
{
char *s = "+1a345";
int a = atoi2(s);
cout << a;
return 0;
}
int atoi2( char *str )
{
assert(str != NULL);
int total = 0;
int signd = 1;
if ( '-' == *str)
{
signd = -1;
str++;
}
else
if ( '+' == *str)
{
str++;
}
char c;
while (c = *str++)
{
assert(c>'0' && c<'9');
total = total*10 + (c - '0');
}
return total*signd;
}
浙公网安备 33010602011771号