把字符串转化为整数的方法

字符串转化为整数可能是实际编程中最常用到的方法了,因为因为string很容易通过下标对每一位的数字进行操作,但是却没办法实现int的加减乘除等,所以在实际编程中经常需要先用string 存下数据,操作完后再转化为int类型

有两种比较实用的方法可以实现

方法一:自己写一个函数来实现

class Solution {
public:
    int StrToInt(string str) 
    {
        int length=str.length();//先计算字符串的长度
        if(length==0)
        {
            return 0;
        }
        int result=0;
        int flag=1;
        int i=0;
        if(str[i]=='-')//只能是在数据的首位输入符号,所以只需要一次判断即可
        {
            flag=-1;
            i++;
        }
        if(str[i]=='+')
        {
            flag=1;
            i++;
        }
        
        while(str[i]!='\0')
        {
            if(str[i]==' ')//删掉数字前面的空格,因为不知道前面输入了多少个空格所以需要在while循环中
            {
                i++;
            }
            if(str[i]>='0'&&str[i]<='9')
            {
                result=(result*10+flag*(str[i]-'0'));
                i++;
            }
            else
            {
                return 0;
            }
        }
        return result;
    }
};

  方法二:调用库函数atio

#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;
int main()
{
    string str;
    cin>>str;
    int result=0;
    result=atoi(str.c_str());
    cout<<result<<endl;
    return 0;
}

  stio函数的头文件是#include<stdlib.h>

string 是C++ STL定义的类型,atoi是 C 语言的库函数,所以要先转换成 char* 类型才可以用 atoi。

atoi函数原型

int atoi(const char *nptr);

  c_str是Borland封装的String类中的一个函数,它返回当前字符串的首字符地址。

posted @ 2018-10-03 22:39  cs_wu  阅读(14004)  评论(0编辑  收藏  举报