C++中string轉int


轉https://blog.csdn.net/xiong452980729/article/details/61677701

C++中string轉int

方法一:使用atoi()函數

函數原型:int atoi(const char *nptr);

函數說明:

atoi( ) 函數會掃描參數 nptr字符串,跳過前面的空白字符(例如空格,tab縮進等,可以通過isspace( )函數來檢測),直到遇上數字或正負符號才開始做轉換,而再遇到非數字或字符串結束時('\0')才結束轉換,並將結果返回。如果 nptr不能轉換成 int 或者 nptr為空字符串,那么將返回 0。

C++中若需要將string類型轉為int類型,需先將string轉為const char*。

函數原型:

const char *c_str();

函數說明:
c_str()函數返回一個指向正規C字符串的指針常量, 內容與本string串相同.這是為了與c語言兼容,在c語言中沒有string類型,故必須通過string類對象的成員函數c_str()把string 對象轉換成c中的字符串樣式。
注意:一定要使用strcpy()函數 等來操作方法c_str()返回的指針 
比如:最好不要這樣: 
char* c; 
string s="1234"; 
c = s.c_str(); //c最后指向的內容是垃圾,因為s對象被析構,其內容被處理,同時,編譯器也將報錯——將一個const char *賦與一個char *。
應該這樣用: 
char c[20]; 
string s="1234"; 
strcpy(c,s.c_str()); 
這樣才不會出錯,c_str()返回的是一個臨時指針,不能對其進行操作
再舉個例子
c_str() 以 char* 形式傳回 string 內含字符串
如果一個函數要求char*參數,可以使用c_str()方法: 
string s = "Hello World!";
printf("%s", s.c_str()); //輸出 "Hello World!"


  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. char* s = "1234";
  9. string str("5678");
  10.  
  11. int intS = atoi(s);
  12.  
  13. //此寫法會報錯
  14. //int intStr = atoi(str);
  15. //需先將string轉成char*
  16. int intStr = atoi(str.c_str());
  17.  
  18. cout << "char* 轉int: " << intS << endl;
  19. cout << "string 轉int: " << intStr << endl;
  20.  
  21. system( "pause");
  22. return 0;
  23. }

 

輸出:


注意:c_str()轉換到第一個非數字字符為止

 

  1. #include<iostream>
  2. #include<string>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. string s("123.aa");
  9. int a = atoi(s.c_str());
  10. cout << a << endl;
  11. system( "pause");
  12. }

 


方法二:使用stringstream

 

C++中將形如"1234"的string字符串轉化為int型整數”里所介紹的方法其實是將string字符串先轉換為C風格的字符串,再利用C語言提供的庫函數atoi將字符串轉換為整型數。這種方法嚴格來說不是C++的做法,因為C++本身就提供了字符串與整型數之間的互換,那就是利用stringstream。下面是使用方法:


 

  1. #include <iostream>
  2. #include <string>
  3. #include <sstream> //要使用stringstream流應包含此頭文件
  4. using namespace std;
  5. int main()
  6. {
  7. stringstream stream; //聲明一個stringstream變量
  8. int n;
  9. string str;
  10. //string轉int
  11. stream << "1234"; //向stream中插入字符串"1234"
  12. stream >> n; //從stream中提取剛插入的字符串"1234"
  13. //並將其賦予變量n完成字符串到int的轉換
  14. cout <<"stringstream string轉int: "<< n << endl; //輸出n
  15. stream.clear(); //同一stream進行多次轉換應調用成員函數clear
  16. //int轉string
  17. stream << 1234; //向stream中插入整型數1234
  18. stream >> str; //從steam中提取剛插入的整型數
  19. //並將其賦予變量str完成整型數到string的轉換
  20. cout << "stringstream int轉string: " << str << endl; //輸出str
  21.  
  22. system( "pause");
  23. return 0;
  24. }

 


輸出:

 


免責聲明!

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



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