atoi、stoi、strtoi區別

首先atoi和strtol都是c裏面的函數,他們均可以將字符串轉爲int,它們的參數都是const char*,所以在用string時,必須調c_str()方法將其轉爲char*的字符串。或者atof,strtod將字符串轉爲double,它們都從字符串開始尋找數字或者正負號或者小數點,而後遇到非法字符終止,不會報異常:函數

int main() {
    using namespace std;
    string strnum=" 232s3112";
    int num1=atoi(strnum.c_str());
    long int num2=strtol(strnum.c_str(),nullptr,10);
    cout<<"atoi的結果爲:"<<num1<<endl;
    cout<<"strtol的結果爲:"<<num2<<endl;
    return 0;
}

輸出結果爲:spa

atoi的結果爲:232
strtol的結果爲:232code

能夠看到,程序在最開始遇到空格跳過,而後遇到了字符's'終止,最後返回了232。blog

這裏要補充的是strtol的第三個參數base的含義是當前字符串中的數字是什麼進制,而atoi則只能識別十進制的。例如:字符串

    using namespace std;
    string strnum="0XDEADbeE";
    int num1=atoi(strnum.c_str());
    long int num2=strtol(strnum.c_str(),nullptr,16);
    cout<<"atoi的結果爲:"<<num1<<endl;
    cout<<"strtol的結果爲:"<<num2<<endl;
    return 0;

輸出結果爲:string

atoi的結果爲:0
strtol的結果爲:233495534

另外能夠注意到的是,若是轉換失敗,這兩個函數不會報錯,而是返回0。class

可是對於stoi就不是這樣了,atoi是string庫中的函數,他的參數是string。程序

int main() {
    using namespace std;
    string strnum="XDEADbeE";
    int num1=atoi(strnum.c_str());
    int num2=stoi(strnum);
    cout<<"atoi的結果爲:"<<num1<<endl;
    cout<<"stoi的結果爲:"<<num2<<endl;
    return 0;
}

程序會報錯:方法

terminate called after throwing an instance of 'std::invalid_argument'
  what():  stoi

咱們把stoi註釋掉再看:call

int main() {
    using namespace std;
    string strnum="XDEADbeE";
    int num1=atoi(strnum.c_str());
    //int num2=stoi(strnum);
    cout<<"atoi的結果爲:"<<num1<<endl;
    //cout<<"stoi的結果爲:"<<num2<<endl;
    return 0;
}

其結果爲:

atoi的結果爲:0

因此在使用時,須要根據實際狀況來選擇。

相關文章
相關標籤/搜索