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
参考资料:
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; }
相关文章推荐
- Sort()函数是c++一
- C语言按行读文件及字符串分割
- 第16章 C++标准模板库STL
- c++学习-字符串
- [C语言]进阶|指针与字符串
- c++中的静态成员
- C++数据访问声明的思考
- PY++ 自动将你的C++程序接口封装供python调用
- c++中的构造函数和析构函数
- Effective C++ Notes
- C++经典面试题(六)
- C++标准库中排序函数sort的用法
- [置顶] C语言游戏_弹弹乐(打砖块)
- C/C++语言基础
- 黑马程序员--c语言动态内存分配
- C++IO对象不可复制或赋值
- 它们,不能是虚函数!!!
- C语言scanf()函数详解
- C语言 关于用户名与密码的存放(文件)
- STL学习笔记-- multiset