C++中stringstream的用法和實例
之前在leetcode中進行string和int的轉(zhuǎn)化時使用過istringstream,現(xiàn)在大致總結(jié)一下用法和測試用例。
介紹:C++引入了ostringstream、istringstream、stringstream這三個類,要使用他們創(chuàng)建對象就必須包含sstream.h頭文件。
istringstream類用于執(zhí)行C++風(fēng)格的串流的輸入操作。
ostringstream類用于執(zhí)行C風(fēng)格的串流的輸出操作。
stringstream類同時可以支持C風(fēng)格的串流的輸入輸出操作。
下圖詳細描述了幾種類之間的繼承關(guān)系:
istringstream是由一個string對象構(gòu)造而來,從一個string對象讀取字符。
ostringstream同樣是有一個string對象構(gòu)造而來,向一個string對象插入字符。
stringstream則是用于C++風(fēng)格的字符串的輸入輸出的。
代碼測試:
#include<iostream> #include <sstream> using namespace std;<pre name="code" class="cpp">int main(){ string test = "-123 9.87 welcome to, 989, test!"; istringstream iss;//istringstream提供讀 string 的功能 iss.str(test);//將 string 類型的 test 復(fù)制給 iss,返回 void string s; cout << "按照空格讀取字符串:" << endl; while (iss >> s){ cout << s << endl;//按空格讀取string } cout << "*********************" << endl; istringstream strm(test); //創(chuàng)建存儲 test 的副本的 stringstream 對象 int i; float f; char c; char buff[1024]; strm >> i; cout <<"讀取int類型:"<< i << endl; strm >> f; cout <<"讀取float類型:"<<f << endl; strm >> c; cout <<"讀取char類型:"<< c << endl; strm >> buff; cout <<"讀取buffer類型:"<< buff << endl; strm.ignore(100, ','); int j; strm >> j; cout <<"忽略‘,'讀取int類型:"<< j << endl; system("pause"); return 0; }
輸出:
總結(jié):
1)在istringstream類中,構(gòu)造字符串流時,空格會成為字符串參數(shù)的內(nèi)部分界;
2)istringstream類可以用作string與各種類型的轉(zhuǎn)換途徑
3)ignore函數(shù)參數(shù):需要讀取字符串的最大長度,需要忽略的字符
代碼測試:
int main(){ ostringstream out; out.put('t');//插入字符 out.put('e'); out << "st"; string res = out.str();//提取字符串; cout << res << endl; system("pause"); return 0; }
輸出:test字符串;
注:如果一開始初始化ostringstream,例如ostringstream out("test"),那么之后put或者<<時的字符串會覆蓋原來的字符,超過的部分在原始基礎(chǔ)上增加。
stringstream同理,三類都可以用來字符串和不同類型轉(zhuǎn)換。
以上就是小編為大家?guī)淼腃++中stringstream的用法和實例全部內(nèi)容了,希望大家多多支持腳本之家~
相關(guān)文章
C語言數(shù)據(jù)結(jié)構(gòu)之二叉樹的非遞歸后序遍歷算法
這篇文章主要介紹了C語言數(shù)據(jù)結(jié)構(gòu)之二叉樹的非遞歸后序遍歷算法的相關(guān)資料,希望通過本文能幫助到大家,讓大家實現(xiàn)這樣的功能,需要的朋友可以參考下2017-10-10C語言中pthread_exit()函數(shù)實現(xiàn)終止線程
本文主要介紹了C語言中pthread_exit()函數(shù)實現(xiàn)終止線程,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05