1、字符串转整型
int StrToInt(const char* str)
{
long long num=0;
const char* copy=str;
if (str!=NULL)
{
bool flag=false;//负数标志
if (*copy=='+')
{
copy++;
}
if (*copy=='-')
{
copy++;
flag=true;
}
while (*copy!='\0')
{
if (*copy>='0' && *copy<='9')
{
num=num*10+(*copy-'0');//关键操作
/*最大值的处理,避免溢出*/
if (num>INT_MAX)
{
num=0;
break;
}
copy++;
}
else //存在异常字符
{
num=0;
break;
}
}
/*若为负数,则取相反数*/
if (*copy=='\0' && flag)
{
num=-num;
}
}
return num;
}
2、整型转字符串
string IntToStr(int number)
{
vector<char> vstr;//转换字符向量
string str;//转换字符串
int temp=0;
bool flag=false;//标记是否为负数
/*对负数和零值进行特殊处理*/
if (number>0)
{
temp=number;
}
else if(number<0)
{
temp=-number;
flag=true;
}
else
{
str=str+'0';
return str;
}
/*提取各位上的数字,存放到vstr向量(倒序)*/
while (temp)
{
char ch=(temp%10)+'0';
vstr.push_back(ch);
temp=temp/10;
}
/*若为负数,则在字符串前添加负号"-"*/
if (flag)
{
str=str+'-';
}
/*将vstr向量中字符顺序追加到字符串str后面*/
int size=vstr.size();
for (int i=size-1; i>=0; i--)
{
str=str+vstr[i];
}
return str;
}