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

以下使用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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值