69,374
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <sstream>
using namespace std;
/*
int main()
{
float f=1.23f;
char buf[32];
sprintf(buf,"%f",f);
cout<<buf<<endl;//1.230000
return 0;
}
*/
/*
int main()
{
float f=1.23f;
char buf[32];
_gcvt(f,7,buf);
cout<<buf<<endl;//1.23
return 0;
}*/
int main()
{
float f=1.23f;
ostringstream oss;
oss<<f;
cout<<oss.str()<<endl;//1.23
return 0;
}
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
int main( )
{
float vf = 1.232f;
stringstream os;
os << vf;
string sf = os.str();
cout << sf << endl;
return 0;
}
对于float f;
方法1:
char buf[32];
snprintf(buf, sizeof(buf), "%f ", f);
string s = buf;
方法2:
#include <stdlib.h>
char buf[32];
_gcvt(f, 16, buf);
string s = buf;
方法3:
#include <sstream>
ostringstream oss;
oss < < f;
string s = oss.str();
方法4:
//使用boost库:
string s = boost::lexical_cast <string> (f);
Example
/* _GCVT.C: This program converts -3.1415e5
* to its string representation.
*/
#include <stdlib.h>
#include <stdio.h>
void main( void )
{
char buffer[50];
double source = -3.1415e5;
_gcvt( source, 7, buffer );
printf( "source: %f buffer: '%s'\n", source, buffer );
_gcvt( source, 7, buffer );
printf( "source: %e buffer: '%s'\n", source, buffer );
}
Output
source: -314150.000000 buffer: '-314150.'
source: -3.141500e+005 buffer: '-314150.'