字符串转换

博客给出了C++中字符串与数值类型转换的代码。定义了from_string和to_string两个模板函数,前者用于将字符串转换为指定类型数值,后者用于将数值转换为字符串。还给出了使用示例,展示了将十六进制字符串转整数、十进制字符串转浮点数的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <strstream>
#include <sstream>

 template <class T>
 bool from_string(T &t, const std::string &s, std::ios_base & (*f)(std::ios_base&))
 {
        std::istringstream iss(s);
        return !(iss>>f>>t).fail();
 };

template<class T>
std::string to_string(const T &tvalue, std::ios_base & (*f)(std::ios_base&))
{
 std::ostrstream oss;
 oss << f << tvalue << '/0';
 return oss.str();
};

#include <sstream>
#include <iostream>

void main()

{

  int i;
  float f;
  // from_string()的第三个参数应为如下中的一个
  // one of std::hex, std::dec 或 std::oct
  if(from_string<int>(i, std::string("ff"), std::hex))
  {
       std::cout<<i<<std::endl;
  }
  else
  {
        std::cout<<"from_string failed"<<std::endl;
  }
  if(from_string<float>(f, std::string("123.456"), std::dec))
  {
       std::cout<<f<<std::endl;
  }
  else{
      std::cout<<"from_string failed"<<std::endl;
  }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值