天天看點

【C++】int轉string,double轉string方法,string轉int,string轉double方法

C++的格式比較多比較複雜,轉換起來有很多方法,我這裡隻提供一種,僅供參考。

int或double轉string

使用字元串流的方式可以比較簡單的完成轉換

需要添加頭檔案

#include <sstream>
           
int iText = 123;
double dText = 123.123;

ostringstream streamInt;
ostringstream streamDouble;

streamInt<< iText;
streamDouble<< dText ;

string strResultInt = streamInt.str();
string strResultDouble = streamDouble.str();
           

使用字元串流的方法的缺點是,如果轉換資料量比較大的時候,可能性能會有一定影響。

另一種轉換方式是使用C庫自帶的sprintf的方法轉換

string轉int和double的方法使用std提供的

string strInt = “321”;
string strDouble = “321.321”;
string strLong = “1234.4321”;

int iResult = std::atoi(strInt.c_str());
double dResult = std::atof(strDouble .c_str());
longlResult = std::atol(strDouble .c_str());
           

  

  

轉載于:https://www.cnblogs.com/duan425/p/5781147.html