2007年3月23日星期五

How to convert double to string in C++(怎样在C++中将double型数据转化为string类型的数据)

t//first the headers
//必要的头文件
#include <sstream> //for stringstream
#include <string> // for string

// Then the codes :
//源代码如下
double aNumber=12.3866e5;
stringstream aStringstream;
aStringstream<<aNumber;
string aString=aStringstream.str();

实际上,上述方法可以用到任意类型到字符串型的转换。
下面是C++发明者的一个FAQ中的例子。
其实也可以回答很多类似的问题
How do I convert a double number to a string?
How do I convert a float number to a string?

How do I convert an integer to a string?

The simplest way is to use a stringstream:
 #include <iostream>
#include <string>
#include <sstream>
using namespace std;

string itos(int i) // convert int to string
{
stringstream s;
s << i;
return s.str();
}

int main()
{
int i = 127;
string ss = itos(i);
const char* p = ss.c_str();

cout << ss << " " <<p <<"\n";
}
Naturally, this technique works for converting any type that you can output using <<to a string.


下面使用模板来转换任意类型的数据为字符
template <class T>
string toString(T i) // convert i to string
{
stringstream s;
s << i;
return s.str();
}

另一种方法:
Make use of reading and parsing a string in memory. It will also allow data type conversion from a string to the type read.
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++StringClass.html
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

main()
{
string test="AAA 123 SSSSS 3.141592654";
istringstream totalSString( test );
string string1, string2;
int integer1;
double PI;

totalSString > string1 > integer1 > string2 > PI;

cout << "Individual parsed variables:" << endl;
cout << "First string: " << string1 << endl;
cout << "First integer: " << integer1 << endl;
cout << "Value of PI: " << PI << endl;
}

没有评论: