stringstream的基本用法

2021-06-27 19:49:44 字數 1192 閱讀 9935

stringstream是字串流。它將流與儲存在記憶體中的string物件繫結起來。在多種資料型別之間實現自動格式化。

1 stringstream物件的使用

#include#includeusing namespace std;

int main()

{ string line,word;

while(getline(cin,line))

{stringstream stream(line);

cout<>word){cout<

輸入:shanghai no1 school 1989

輸出:shanghi no1 school 1989

shanghai

no1school

1989

2stringstream提供的轉換和格式化

#include#includeusing namespace std;

int main()

{ int val1 = 512,val2 =1024;

stringstream ss;

ss<<"val1: "<>dump>>a

>>dump>>b;

cout<

輸出為:val1: 512

val2: 1024

512 1024

第一處黑體字部分:將int型別讀入ss,變為string型別

第二處黑體字部分:提取512,1024儲存為int型別。當然,如果a,b宣告為string型別,那麼這兩個字面值常量相應儲存為string型別

3其他注意

stringstream不會主動釋放記憶體(或許是為了提高效率),但如果你要在程式中用同乙個流,反覆讀寫大量的資料,將會造成大量的記憶體消 耗,因些這時候,需要適時地清除一下緩衝 (用 stream.str("") )

#include #include#includeusing namespace std;

int main()

{ stringstream ss;

string s;

ss<<"shanghai no1 school";

ss>>s;

cout<<"size of stream = "<

輸出:size of stream = 19

s: shanghai

size of stream = 0

stringstream的基本用法

stringstream是字串流。它將流與儲存在記憶體中的string物件繫結起來。在多種資料型別之間實現自動格式化。1 stringstream物件的使用 include include using namespace std intmain return0 輸入 shanghai no1 sch...

stringstream的基本用法

stringstream是字串流。1 stringstream物件的使用 按空格分割 include includeusing namespace std int main string line,word while getline cin,line stringstream stream lin...

stringstream的基本用法

1.include include using namespace std int main 輸入 shanghai no1 school 1989 輸出 shanghi no1 school 1989 shanghai no1 school 1989 include include using n...