利用stringstream构造一个函数,可以将任意类型转换为string类型。
//构造一个任意类型转换string类型的函数
template<class T>
void toString(string &s, const T &t)
{
stringstream ss;
ss << t;
s = ss.str();
//或ss >> s;
}
利用stringstream构造一个函数,可以将任意类型转换为任意类型。
//构造一个任意类型转换任意类型的函数
template<class outT, class inT>
outT convert(const inT &in)
{
stringstream ss;
outT out;
ss << in;
ss >> out;
return out;
}
执行结果如下:
函数toString()
string str1, str2, str3;
double dnum = 123.456;
toString(str1, dnum);
//或者使用toString<double>(str1, dnum);
cout << "str1: " << str1 << endl;
//输出str1: 123.456
函数convert()
float fnum = 456.123;
str2 = convert<string>(fnum);
//或者使用str2 = convert<string, float>(fnum);
cout << "str2: " << str2 << endl;
//输出str1: 456.123
此外,string中的空格将会阻断转换
int a;
double b;
str3 = "1 23.789";
a = convert<int>(str3);
b = convert<double>(str3);
cout << "a: " << a << "; " << "b: " << b << endl;
//输出a: 1; b: 1
如果采用istringstream则会分别赋值
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
istringstream istr;
istr.str("1 56.7");
//上述两个过程可以简单写成 istringstream istr("1 56.7");
cout << istr.str() << endl;
int a;
float b;
istr >> a;
cout << a << "; ";
istr >> b;
cout << b << endl;
return 0;
}
//输出1; 56.7
完整代码如下:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
//构造一个任意类型转换string类型的函数
template<class T>
void toString(string &s, const T &t)
{
stringstream ss;
ss << t;
s = ss.str();
//ss >> s;
}
//构造一个任意类型转换任意类型的函数
template<class outT, class inT>
outT convert(const inT &in)
{
stringstream ss;
outT out;
ss << in;
ss >> out;
return out;
}
int main()
{
string str1, str2, str3;
double dnum = 123.456;
toString(str1, dnum);
//或者使用toString<double>(str1, dnum);
cout << "str1: " << str1 << endl;
float fnum = 456.123;
str2 = convert<string>(fnum);
//或者使用str2 = convert<string, float>(fnum);
cout << "str2: " << str2 << endl;
int a;
double b;
str3 = "1 23.789";
a = convert<int>(str3);
b = convert<double>(str3);
cout << "a: " << a << "; " << "b: " << b << endl;
return 0;
}
PS:在进行多次转换的时候,两次转换之间必须调用stringstream的成员函数clear()