c++ 利用stringstream进行类型转换
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
template<typename From, typename To>
bool typeCaste(const From& from, To& to) {
std::stringstream ss;
if (!(ss<<from && ss>>to && ss.eof())) {
return false;
}
return true;
}
int main() {
string a = "hello 123 456";
stringstream ss;
ss << a;
string key;
int v1, v2;
ss >> key >> v1 >> v2;
cout<<key<<endl;
cout<<v1<<endl;
cout<<v2<<endl;
string from = "";
double to;
bool flag = typeCaste(from, to);
cout<<flag<<endl;
cout<<to<<endl;
from = "123.456";
flag = typeCaste(from, to);
cout<<flag<<endl;
cout<<to<<endl;
return 0;
}
结果:
hello
123
456
0
8.33705e-315
1
123.456