C++ - string類型轉換int類型


C語言轉換形式:

...
std::string str;
int i = atoi(str.c_str());
...

其參數只能是字符數組,不能是string類型,還有一類函數strtod

 atof()     將字符串轉換為雙精度浮點型值
 atoi()     將字符串轉換為整型值
 atol()     將字符串轉換為長整型值
 strtod()   將字符串轉換為雙精度浮點型值,並報告不能被轉換的所有剩余數字
 strtol()   將字符串轉換為長整值,並報告不能被轉換的所有剩余數字

C++轉換格式(C++11):

...
std::string str;
int i = std::stoi(str);
...

同樣, 可以使用 stol(long), stof(float), stod(double) 等.

 

參考鏈接:

1. https://blog.csdn.net/caroline_wendy/article/details/29390573

2. http://c.biancheng.net/cpp/html/1574.html


免責聲明!

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



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