您的位置:首页 > 编程语言 > C语言/C++

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

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

参考资料:

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

2:C++模板(很详细,有例子):/article/4968577.html

#include <iostream>
#include <sstream>
using namespace std;
// http://www.cnblogs.com/waitingandhoping/p/4604124.html /*

由于stringstream构造、解析函数很耗时,所以尽量只创建一个。
stream.clear(); // 只是重置了stringstream的状态标志,并没有清空数据
stream.str(""); // 清空数据

*/

// 其他类型 -> string
template <class Type>
void TypeTostring(Type TypeTmp, string& strTmp) {
stringstream stream;
stream << TypeTmp;
stream >> strTmp;
stream.clear();
stream.str("");
}

// string -> 为其他类型
template <class Type>
void stringToType(string strTmp, Type& TypeTmp) {
stringstream stream;
stream << strTmp;
stream >> TypeTmp;
stream.clear();
stream.str("");
}

int main() {    // 测试

string strTmp;
int intTmp;
__int64 int64Tmp;
double dbeTmp;

while (true) {
cout << "----- int to string -----" << endl;
cin >> intTmp;
TypeTostring(intTmp, strTmp);
cout << strTmp << endl;
cout << "----- string to int -----" << endl;
cin >> strTmp;
stringToType(strTmp, intTmp);
cout << intTmp  << endl;

cout << "----- double to string -----" << endl;
cin >> dbeTmp;
TypeTostring(dbeTmp, strTmp);
cout << strTmp << endl;
cout << "----- string to double -----" << endl;
cin >> strTmp;
stringToType(strTmp, dbeTmp);
cout << dbeTmp << endl;

cout << "----- int64 to string -----" << endl;
cin >> int64Tmp;
TypeTostring(int64Tmp, strTmp);
cout << strTmp << endl;
cout << "----- string to int64 -----" << endl;
cin >> strTmp;
stringToType(strTmp, int64Tmp);
cout << int64Tmp << endl;
cout << "--------------------------end-------------------------" << endl;
}
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: