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

C++ 字符串与数值型的相互转换

2018-04-06 22:52 387 查看
以下使用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息