c++ custom string format using stringstreams -
i trying use new stringstreams method convert float+int combination format trying see if there better way handle this:
now using //string string = static_cast( &(ostringstream() << number) )->str(); kind of mode - how can stored string form of format - "1.10(3)". precision equal decimals. catch here none of these values constants. if solution can't in-line function or stringstreams - it's fine long it's generic enough. note in end plan use string gdi text string.
thanks in advance - if 1 can help.
here current sample code(and looking alternate efficient way done):
string convert(float number,int decimals) { std::ostringstream buff; buff<<setprecision(decimals)<<fixed<<number; return buff.str(); } float f=1.1; // can have values 1,1.5 or 1.52 int decimals=2; //dynamic number - calculated other means - not fixed number int i=3; // dynamic number - calculated other means string s=convert(f,decimals)+"("+convert(i,0)+")"; // output - 1.10(3)
you can use std::fixed
, std::setprecision
, std::setw
, std::setfill
defined in <iomanip>
:
float f=1.1; int decimals=2; int i=3; ostringstream ss; ss << std::fixed << std::setprecision(decimals) << f << '(' << << ')'; string str = ss.str();
which outputs :
1.10(3)
you can configure stringstream , keep configuration :
ostringstream ss; ss.precision(5); ss.setf(std::ios::fixed);
edit
you can still in 1 line if really want :
string str = ((ostringstream&)(ostringstream() << fixed << setprecision(decimals) << f << '(' << << ')')).str();
if want lpcwstr
(const wchar_t *
) instead of lpcstr
(const char*
) should use wstringstream
instead of stringstream
.
ostringstream ss; string str = ss.str(); lpcstr* c_str = str.c_str(); wostringstream wss; wstring wstr = wss.str(); lpcwstr* wc_str = wstr.c_str();
if want lpctstr
(lpcstr
or lpcwstr
if unicode
defined), can use typedef
:
typedef std::basic_string<tchar> tstring; typedef std::basic_ostringstream<tchar , std::char_traits<tchar> > tstringstream; tostringstream tss; tstring tstr = tss.str(); lpctstr* tc_str = tstr.c_str();
tchar char *
if unicode
not defined in project , wchar_t *
if unicode
defined.