[C++] string與int, float, double相互轉換

來源:互聯網
上載者:User

標籤:

參考:http://blog.csdn.net/candadition/article/details/7342380

 

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

# 方法一: 使用stringstream

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

Demo:

#include <iostream>  #include <sstream>    //使用stringstream需要引入這個標頭檔  using namespace std;    //模板函數:將string類型變數轉換為常用的數實值型別(此方法具有普遍適用性)  template <class Type>  Type stringToNum(const string& str)  {      istringstream iss(str);      Type num;      iss >> num;      return num;      }    int main(int argc, char* argv[])  {      string str("00801");      cout << stringToNum<int>(str) << endl;        system("pause");      return 0; 

輸入結果 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:

#include <iostream>  using namespace std;  int main ()  {      int i;      char szInput [256];      cout<<"Enter a number: "<<endl;      fgets ( szInput, 256, stdin );      i = atoi (szInput);      cout<<"The value entered is :"<<szInput<<endl;      cout<<" The number convert is:"<<i<<endl;      return 0;  } 

輸出

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:

/* atof example: sine calculator */  #include <stdio.h>  #include <stdlib.h>  #include <math.h>  int main ()  {    double n,m;    double pi=3.1415926535;    char szInput [256];    printf ( "Enter degrees: " );    gets ( szInput );    //char類型轉換為double類型     n = atof ( szInput );    m = sin (n*pi/180);    printf ( "The sine of %f degrees is %f\n" , n, m );        return 0;  }  

 

 

 

 

 

C++ int類型轉換string類型

參考:http://blog.csdn.net/candadition/article/details/7342092

C++中不像C#或Java中能直接使用字串加法將 int類型轉換為string類型。C++中進行這樣的類型轉換需要一些額外的函數。

一、C++的int轉string

 #方法一: 使用itoa函數:    char *  itoa ( int value, char * str, int base );                            

說明:Convert integer to string (non-standard function)

參數:

·value : Value to be converted to a string.·str : Array in memory where to store the resulting null-terminated string.·base : Numerical base used to represent the value as a string, between2 and36, where10 means decimal base, 16 hexadecimal,8 octal, and2 binary.

Demo:

#include <iostream> using namespace std; int main(int argc, char* argv[])  {        int n = 30;     char c[10];       //二進位轉換    itoa(n, c, 2);      cout << "2-> " << c << endl;     //十進位轉換    itoa(n, c, 10);        cout << "10-> " <<  c << endl;    //十六進位轉換    itoa(n, c, 16);         cout << "16-> " <<  c << endl;     system("pause");         return 0;  }

輸出:

2-> 11110  
10-> 30  
16-> 1e  

#方法二: 使用sprintf:   int sprintf ( char * str, const char * format, ... );

參數說明:

% 印出百分比符號,不轉換。b 整數轉成二進位。c 整數轉成對應的 ASCII 字元。d 整數轉成十進位。f 倍精確度數字轉成浮點數。o 整數轉成八進位。s 整數轉成字串。x 整數轉成小寫十六進位。X 整數轉成大寫十六進位。

Demo:

#include <iostream>#include <string>using namespace std;  int main() {         int n = 30;     char c[20];     //char *c;    //%d十進位    sprintf(c, "%d", n);       cout << c << endl;        //%o八進位    sprintf(c, "%o", n);       cout << c << endl;       //%X大寫十六進位    sprintf(c, "%X", n);       cout << c << endl;      //%cACSII字元    sprintf(c, "%c", n);       cout << c << endl;          //%f浮點數轉換    float f = 24.678;        sprintf(c, "%f", f);     cout << c << endl;       //%.2f"保留小數點後面兩位    sprintf(c, "%.2f", f);        cout << c << endl;      //轉換兩個數    sprintf(c, "%d-%.2f", n, f);      cout << c << endl;      system("pause");        return 0;  }  

輸出:

30  
36  
1E  
//注:這裡是個特殊符號  
24.677999  
24.68  
30-24.68  


#方法三:使用stringstream

Input/output string stream class: 

stringstream provides an interface to manipulate strings as if they were input/output streams.


 
#include <iostream> #include <string>#include <sstream>    //引入stringstream標頭檔using namespace std; int main() {         stringstream strStream;      int a = 100;      float f = 23.5566;     //int、float類型都可以塞到stringstream中    strStream << a << "----"<< f ;     string s = strStream.str();      cout << s << endl;      system("pause");        return 0;  }

輸出:

100----23.5566  

 #四、其他

1.sprintf可能引起緩衝區溢位,可以考慮使用 snprintf 或者非標準的 asprintf

2.如果是mfc程式,可以使用 CString::Format

3.如果使用boost,則可以直接使用: string s = boost::lexical_cast <string>(a);

4.atoi 也是不可移植的。





 

 

 

 

 

 

[C++] string與int, float, double相互轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.