C++ string 与 int 等类型 的相互转换

看到网上有许多关于这个的实现,而且会涉及到细节的处理。为了以后方便的使用,在此提供可以直接可以使用的函数。

 参考资料:

1:讲解C++ stringstream(细节):http://blog.csdn.net/leonardwang/article/details/4881122

2:C++模板(很详细,有例子):http://www.cnblogs.com/gaojun/archive/2010/09/10/1823354.html

 1 #include <iostream>
 2 #include <sstream>
 3 using namespace std;
 4 // http://www.cnblogs.com/waitingandhoping/p/4604124.html
 5 /*
 6 
 7 由于stringstream构造、解析函数很耗时,所以尽量只创建一个。
 8 stream.clear(); // 只是重置了stringstream的状态标志,并没有清空数据
 9 stream.str(""); // 清空数据
10 
11 */
12 
13 // 其他类型 -> string
14 template <class Type>
15 void TypeTostring(Type TypeTmp, string& strTmp) { 
16     stringstream stream;
17     stream << TypeTmp;
18     stream >> strTmp;
19     stream.clear();
20     stream.str("");
21 }
22 
23 // string -> 为其他类型
24 template <class Type>
25 void stringToType(string strTmp, Type& TypeTmp) {
26     stringstream stream;
27     stream << strTmp;
28     stream >> TypeTmp;
29     stream.clear();
30     stream.str("");
31 }
32 
33 int main() {    // 测试
34 
35     string strTmp;
36     int intTmp;
37     __int64 int64Tmp;
38     double dbeTmp;
39 
40     while (true) {
41         cout << "----- int to string -----" << endl;
42         cin >> intTmp;
43         TypeTostring(intTmp, strTmp);
44         cout << strTmp << endl;
45         cout << "----- string to int -----" << endl;
46         cin >> strTmp;
47         stringToType(strTmp, intTmp);
48         cout << intTmp  << endl;
49 
50 
51         cout << "----- double to string -----" << endl;
52         cin >> dbeTmp;
53         TypeTostring(dbeTmp, strTmp);
54         cout << strTmp << endl;
55         cout << "----- string to double -----" << endl;
56         cin >> strTmp;
57         stringToType(strTmp, dbeTmp);
58         cout << dbeTmp << endl;
59 
60 
61         cout << "----- int64 to string -----" << endl;
62         cin >> int64Tmp;
63         TypeTostring(int64Tmp, strTmp);
64         cout << strTmp << endl;
65         cout << "----- string to int64 -----" << endl;
66         cin >> strTmp;
67         stringToType(strTmp, int64Tmp);
68         cout << int64Tmp << endl;
69         cout << "--------------------------end-------------------------" << endl;
70     }
71     return 0;
72 }

 

 

posted @ 2015-06-27 15:24  JmingS  阅读(1843)  评论(1编辑  收藏  举报