C++中有字符串转为整数的函数atoi,比较简单就不解释了,多看源码多多思考,
源码如下:
#include "stdafx.h"
#include <cctype>
#include <assert.h>
int my_atoi(const char *p){
assert(p != NULL);
bool neg_flag = false;
int res = 0;
if (p[0] == '+' || p[0] == '-')
{
neg_flag = (*p++ != '+');
}
while (*p >= '0' && *p <= '9')
{
res = res * 10 + (*p++ - '0');
}
return neg_flag ? 0-res : res;
}