码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-06-27 16:14:41      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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

 参考资料:

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 
 5 
 6 //由于stringstream构造、解析函数很耗时,所以尽量只创建一个。
 7 template <class Type>    // 要与string转换的类型
 8 Type stringAndType(Type strTmp) {    // string 与 其他类型 互相转换
 9     stringstream stream;
10     stream << strTmp;
11     Type TypeTmp;
12     stream >> TypeTmp;
13     stream.clear(); // 只是重置了stringstream的状态标志,并没有清空数据
14     stream.str(""); // 清空数据 
15     return TypeTmp;
16 }
17 
18 int main() {    // 测试
19 
20     string strTmp;
21     int intTmp;
22     __int64 int64Tmp;
23     double dbeTmp;
24 
25     while (true) {
26         cout << "----- int to string -----" << endl;
27         cin >> intTmp;
28         cout << stringAndType(intTmp) << endl;
29         cout << "----- string to int -----" << endl;
30         cin >> strTmp;
31         cout << stringAndType(strTmp) << endl;
32 
33 
34         cout << "----- double to string -----" << endl;
35         cin >> dbeTmp;
36         cout << stringAndType(dbeTmp) << endl;
37         cout << "----- string to double -----" << endl;
38         cin >> strTmp;
39         cout << stringAndType(strTmp) << endl;
40 
41 
42         cout << "----- int64 to string -----" << endl;
43         cin >> int64Tmp;
44         cout << stringAndType(int64Tmp) << endl;
45         cout << "----- string to int64 -----" << endl;
46         cin >> strTmp;
47         cout << stringAndType(strTmp) << endl;
48         cout << "--------------------------end-------------------------" << endl;
49     }
50     return 0;
51 }

 

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

标签:

原文地址:http://www.cnblogs.com/waitingandhoping/p/4604124.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!