atoi、stoi、strtoi區別
阿新 • • 發佈:2018-12-10
首先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; }
輸出結果為:
atoi的結果為:232 strtol的結果為:232
可以看到,程式在最開始遇到空格跳過,然後遇到了字元's'終止,最後返回了232。
這裡要補充的是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;
輸出結果為:
atoi的結果為:0 strtol的結果為:233495534
另外可以注意到的是,如果轉換失敗,這兩個函式不會報錯,而是返回0。
但是對於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註釋掉再看:
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
所以在使用時,需要根據實際情況來選擇。