http://blog.csdn.net/v_JULY_v/article/details/6347454(原博文地址)
将字符串转化成数字要考虑很多问题:1,字符串是否为空;2,字符串的开头有可能不是数字的字母形式,而是‘+’或者'-';3,字符串中有可能不是数字对应的字母;4,字符串转换之后有可能越界。
下面给出代码:比较欣赏的是其中的assert.
#include<iostream>
#include<string>
#include<assert.h>
using namespace std;
int str_to_int(string str)
{
assert(str.size()>0);
int pos=0;
int symbol=1;
if(str[pos]=='+')
pos++;
else if(str[pos]=='-')
{
pos++;
symbol=-1;
}
int num=0;
while(pos<str.size())
{
assert(str[pos]>='0');
assert(str[pos]<='9');
num=num*10+(str[pos]-'0');
pos++;
assert(num>0);
}
num*=symbol;
return num;
}
void main()
{
char str[]="-23455";
int num=str_to_int(str);
cout<<num<<endl;
}