字串流sstream part1 基本知識

2022-04-06 23:40:43 字數 1560 閱讀 5307

c++中的輸入輸出分為三種:基於控制台的i/o,即istream、ostream、iostream;基於檔案的i/o,即ifstream、ofstream、fstream;基於字串的i/o,即istringstream、ostringstream、stringstream.

c++引入了ostringstream、istringstream、stringstream這三個類,要使用它們建立物件就必須包含標頭檔案sstream。其中ostringstream繼承自ostream、istringstream繼承自istream、stringstream繼承自iostream。這三個類內部除了擁有string buffer之外,還保持了一系列的從ios_base和ios繼承而來的格式化字段,因此可以格式化輸入/輸出。

ostringstream的構造

ostringstream (ios_base::openmode which = ios_base::out);

ostringstream (const string& str, ios_base::openmode which = ios_base::out);

ostringstream的方法

string str() const;                --    將字串緩衝區中的內容複製到乙個string物件中,並返回該物件

void str(const string& s);      --    清除緩衝區原有資料並將字串s送入字串緩衝區

istringstream的構造

istringstream (ios_base::openmode which = ios_base::in);

istringstream (const string& str, ios_base::openmode which = ios_base::in);

istringstream的方法

string str() const;                --    將字串緩衝區中的內容複製到乙個string物件中,並返回該物件

void str(const string& s);      --    清除緩衝區原有資料並將字串s送入字串緩衝區

stringstream的構造

stringstream (ios_base::openmode which = ios_base::in | ios_base::out);

stringstream (const string& str, ios_base::openmode which = ios_base::in | ios_base::out);

stringstream的方法

string str() const;                --    將字串緩衝區中的內容複製到乙個string物件中,並返回該物件

void str(const string& s);      --    清除緩衝區原有資料並將字串s送入字串緩衝區

#include #include 

#include

using

namespace

std;

intmain()

STL之Stringstream字串流使用總結

如果你已習慣了風格的轉換,也許你首先會問 為什麼要花額外的精力來學習基於的型別 轉換呢?也許對下面乙個簡單的例子的回顧能夠說服你。假設你想用sprintf 函式將乙個變數從int型別轉換到字串型別。為了正確地完成這個任 務,你必須確保證目標緩衝區有足夠大空間以容納轉換完的字串。此外,還必須使用正確的...

STL之Stringstream字串流使用總結

如果你已習慣了風格的轉換,也許你首先會問 為什麼要花額外的精力來學習基於的型別 轉換呢?也許對下面乙個簡單的例子的回顧能夠說服你。假設你想用sprintf 函式將乙個變數從int型別轉換到字串型別。為了正確地完成這個任 務,你必須確保證目標緩衝區有足夠大空間以容納轉換完的字串。此外,還必須使用正確的...

C 檔案流 字串流

include include include include include include using namespace std ifstream in void except catch int main char a,b string str,word,str1,str2 sssssss ...