C++ 字符串与数值型的相互转换
2018-04-06 22:52
387 查看
以下使用stringstream进行字符串与数值型的相互转换,这种转换方式更方便安全可靠。
stringstream的相关介绍不再做相关描述。
stringstream的相关介绍不再做相关描述。
#include "stdafx.h" #include <iostream> #include <sstream> using namespace std; // 将整型数据转为字符串 std::string intos(int iValue) { stringstream s; s << iValue; // 将数值型输入到缓冲区中 string strValue = ""; // 获取字符串的第一种方式 s >> strValue; // 获取字符串的第二种方式 strValue = s.str(); // 输出转换后的字符串。 s.clear(); // 清空 return strValue; } // 使用模板,将数值型转为字符串 template <class T> std::string ToString(const T& t) { stringstream oos; oos << t; string strValue; oos >> strValue; return strValue; } // 使用模板,将数值型转为字符串 template <class T> void TValueToString(const T& t, string& strValue) { strValue = ToString(t); } // 数值型与字符型互转 template <class in_value, class out_value> out_value ValueConvert(const in_value& inValue) { stringstream s; s << inValue; out_value outValue; s >> outValue; return outValue; } // 测试 void Test() { double d = 212323; float f = 2323.2323; int i = 2323; string strValue = ""; TValueToString(d, strValue); cout << "strValue:" << strValue << endl; strValue = ""; TValueToString(f, strValue); cout << "strValue:" << strValue << endl; strValue = ""; TValueToString(i, strValue); cout << "strValue:" << strValue << endl; }
相关文章推荐
- C++数值与字符串相互转换
- C/C++中字符串与数字相互转换
- 44、数值型数据与字符串的相互转换
- C++使用模板实现数值型字符串类型间的转换
- C/C++时间相关操作 SYSTEMTIME time_t 字符串的相互转换
- C/C++中字符串与数字相互转换
- Java中数值型,字符型及字符串的相互转换
- C/C++ 字符串与数字相互转换
- c++中的字符串与数字相互转换
- 二进制值和十六进制字符串相互转换的C++代码
- C++中数字与字符串的相互转换
- C++ 整型和字符串相互转换
- C/C++中ASCII与Unicode字符串相互转换
- 『C/C++』整型和字符串相互转换
- C/C++中字符串与数字相互转换
- C++中字符串与数字相互转换
- C++中字符串-数字相互转换
- c/c++字符串拼接追加复制,字符串和int相互转换,sscanf的转义
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换