C++中將string類型轉換為int, float, double類型 主要通過以下幾種方式:


 

C++中將string類型轉換為int, float, double類型 主要通過以下幾種方式:

# 方法一: 使用stringstream

stringstream在int或float類型轉換為string類型的方法中已經介紹過, 這里也能用作將string類型轉換為常用的數值類型。

Demo:

[cpp]  view plain copy
 
  1. #include <iostream>  
  2. #include <sstream>    //使用stringstream需要引入這個頭文件  
  3. using namespace std;  
  4.   
  5. //模板函數:將string類型變量轉換為常用的數值類型(此方法具有普遍適用性)  
  6. template <class Type>  
  7. Type stringToNum(const string& str)  
  8. {  
  9.     istringstream iss(str);  
  10.     Type num;  
  11.     iss >> num;  
  12.     return num;      
  13. }  
  14.   
  15. int main(int argc, char* argv[])  
  16. {  
  17.     string str("00801");  
  18.     cout << stringToNum<int>(str) << endl;  
  19.   
  20.     system("pause");  
  21.     return 0;  
  22. }  

輸出結果:

 

  801
 請按任意鍵繼續. . .

 

  #方法二:使用atoi()、 atil() 、atof()函數  -----------------實際上是char類型向數值類型的轉換

注意:使用 atoi 的話,如果 string s 為空,返回值為0.則無法判斷s是0還是空

1. atoi():      int atoi ( const char * str );

說明:Parses the C string str interpreting its content as an integral number, which is returned as an int value.

參數:str : C string beginning with the representation of an integral number.

返回值:1. 成功轉換顯示一個Int類型的值.  2. 不可轉換的字符串返回0.  3.如果轉換后緩沖區溢出,返回 INT_MAX orINT_MIN

Demo:

[cpp]  view plain copy
 
  1. #include <iostream>  
  2. using namespace std;  
  3. int main ()  
  4. {  
  5.     int i;  
  6.     char szInput [256];  
  7.     cout<<"Enter a number: "<<endl;  
  8.     fgets ( szInput, 256, stdin );  
  9.     i = atoi (szInput);  
  10.     cout<<"The value entered is :"<<szInput<<endl;  
  11.     cout<<" The number convert is:"<<i<<endl;  
  12.     return 0;  
  13. }  

輸出:

Enter a number: 48

The value entered is : 48

The number convert is: 48

 

2.aotl():  long int atol ( const char * str );

說明:C string str interpreting its content as an integral number, which is returned as a long int value(用法和atoi函數類似,返回值為long int)

3.atof():  double atof ( const char * str );

參數:C string beginning with the representation of a floating-point number.

返回值:1. 轉換成功返回doublel類型的值 2.不能轉換,返回0.0。  3.越界,返回HUGE_VAL

Demo:

[cpp]  view plain copy
 
  1. /* atof example: sine calculator */  
  2. #include <stdio.h>  
  3. #include <stdlib.h>  
  4. #include <math.h>  
  5. int main ()  
  6. {  
  7.   double n,m;  
  8.   double pi=3.1415926535;  
  9.   char szInput [256];  
  10.   printf ( "Enter degrees: " );  
  11.   gets ( szInput );  
  12.   //char類型轉換為double類型   
  13.   n = atof ( szInput );  
  14.   m = sin (n*pi/180);  
  15.   printf ( "The sine of %f degrees is %f\n" , n, m );  
  16.     
  17.   return 0;  
  18. }  


免責聲明!

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



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