C++ std::stringstream

一 简介

stringstream可以很方便的进行数字与字符串的转换。

头文件<sstream>

template< 
    class CharT, 
    class Traits = std::char_traits<CharT>
> class basic_stringstream;
(until C++11)
template< 
    class CharT, 
    class Traits = std::char_traits<CharT>,
    class Allocator = std::allocator<CharT>
> class basic_stringstream; (since C++11)

stringstream	basic_stringstream<char>

派生层次:

(图片引用自cppreference),因此从std::ios_base等父类继承了大量成员函数。

二 例子

#include <iostream>
#include <iomanip>
#include <sstream>

int main() {
  {
    std::cout << std::endl;
    std::cout << 1 << std::endl;

    std::stringstream sm;
    sm << 12345;
    sm << "@163.com";
    std::cout << "sm.str(): " << sm.str() << std::endl;
  }
  {
    std::cout << std::endl;
    std::cout << 2 << std::endl;

    std::stringstream sm;
    sm << "54321@163.com";
    int i  = 0;
    sm >> i;
    std::cout << "i: " << i << std::endl;
  }
  {
    std::cout << std::endl;
    std::cout << 3 << std::endl;

    std::stringstream sm;
    sm << std::setfill('0') << std::setw(4) << 1;
    std::cout << "sm.str(): " << sm.str() << std::endl;
    sm.str("");
    sm << "0x" << std::hex << 123456;
    std::cout << "sm.str(): " << sm.str() << std::endl;
  }

  std::cin.get();

  return 0;
}

三 参考

cppreference 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值