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 << "[email protected]";
    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 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章