C++ 字符串轉換為數字


atoi
 

相同點:

①都是C++的字符處理函數,把數字字符串轉換成int輸出

②頭文件都是#include<cstring>

不同點:

①atoi()的參數是 const char* ,因此對於一個字符串str我們必須調用 c_str()的方法把這個string轉換成 const char*類型的,而stoi()的參數是const string*,不需要轉化為 const char*;

如圖:

②stoi()會做范圍檢查,默認范圍是在int的范圍內的,如果超出范圍的話則會runtime error!

如圖:

 

而atoi()不會做范圍檢查,如果超出范圍的話,超出上界,則輸出上界,超出下界,則輸出下界;

代碼:

 
  1. //myfirst.cpp--displays a message

  2.  
  3. #include "stdafx.h"

  4. #include <iostream>

  5. #include <set>

  6. #include <string>

  7. using namespace std;

  8. int main()

  9. {

  10. string s1 = "2147482", s2 = "-214748";

  11. string s3 = "214748666666663", s4 = "-21474836488";

  12. cout << stoi(s1) << endl;

  13. cout << stoi(s2) << endl;

  14. cout << atoi(s3.c_str()) << endl;

  15. cout << atoi(s4.c_str()) << endl;

  16. return 0;

  17. }

控制台:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM