面试题49—把字符串转化成整数

来源:互联网 发布:流量防火墙软件 编辑:程序博客网 时间:2024/06/06 04:34

代码示例:

#include<iostream>using namespace std;bool flag;int StrToInt(const char *str){    int num = 0;    flag = false;    if (str == NULL || *str == '\0')//处理空指针和空串    {        return num;    }    const char *temp = str;    bool minus = false;    if (*temp == '+')//处理首位是'+'的情况    {        temp++;        if (*temp == '\0')//处理只有一个‘+’的情况        {            return num;        }    }    else if (*temp == '-')//处理首位是'-'的情况    {        temp++;        minus = true;        if (*temp == '\0')//处理只有一个‘-’的情况        {            return num;        }    }    while (*temp != '\0')    {        if ('0' <= *temp&&*temp <= '9')        {            num = num * 10 + *temp - '0';            temp++;        }        else        {            break;        }    }    if (*temp == '\0')    {        flag = true;        if (minus)            num = 0 - num;//需要考虑溢出        return num;    }    else    {        flag = false;        return 0;    }}int main(){    const char *str = "-5896123";    int res = StrToInt(str);    if (flag)    {        cout << "字符串" << str << "转化成整数:" << res << endl;    }    else    {        cout << "输入有误!" << endl;    }}