字符串与其他类型之间的转换

该功能是使用字符流的方式实现的,使用模板的方式,实现多种不同的类型转换

需要添加头文件#include <sstream>

 1 #include <string>
 2 #include <sstream>
 3 
 4 //数据类型转换string -> T
 5 template <class T>
 6 T StringTo(std::string s)
 7 {
 8     T value;
 9     std::stringstream(s) >> value;
10     return value;
11 }
12 
13 //T->String
14 template <class T>
15 std::string ToString(T value)
16 {
17     std::stringstream ss;
18     ss << value;
19     return ss.str();
20 }

 

使用展示:

 1 using namespace std;
 2 int main()
 3 {
 4     string strTestNum = "100";
 5     int num = 0;
 6 
 7     num = StringTo<int>(strTestNum);
 8     cout<<"string["<<strTestNum<<"]int["<<num<<"]"<<endl;
 9 
10     num = num*2;
11     strTestNum = ToString<int>(num);
12     cout<<"string["<<strTestNum<<"]int["<<num<<"]"<<endl;
13     return 0;
14 }

 

运行展示:

转载请标明出处:http://www.cnblogs.com/rjdeng/

posted @ 2016-04-08 11:24  我不懂编程  阅读(105)  评论(0)    收藏  举报