1. 程式人生 > >C++基礎教程面向物件(學習筆記(104))

C++基礎教程面向物件(學習筆記(104))

字串的流類

到目前為止,您所看到的所有I / O示例都是寫入cout或從cin讀取。但是,還有另一組類稱為字串的流類,允許您使用熟悉的插入(<<)和提取(>>)運算子來處理字串。與istream和ostream一樣,字串流提供了一個緩衝區來儲存資料。但是,與cin和cout不同,這些流不連線到I / O通道(例如鍵盤,監視器等)。字串流的主要用途之一是緩衝輸出以便稍後顯示,或逐行處理輸入。

字串有六個流類:istringstream(從istream派生),ostringstream(從ostream派生)和stringstream(從iostream派生)用於讀取和寫入普通字元寬度字串。wistringstream,wostringstream和wstringstream用於讀取和寫入寬字串。要使用字串流,您需要#include sstream標頭。

有兩種方法可以將資料匯入字串流:

1)使用insert(<<)運算子:

stringstream os;
os << "en garde!" << endl; // 插入“en garde!”進入stringstream

2)使用str(string)函式設定緩衝區的值:

stringstream os;
os.str("en garde!"); // 將stringstream緩衝區設定為“en garde!”

同樣有兩種方法可以從字串流中獲取資料:

1)使用str()函式檢索緩衝區的結果:

stringstream os;
os << "12345 67.89" << endl;
cout << os.str();

這列印:

12345 67.89
2)使用提取(>>)運算子:

stringstream os;
os << "12345 67.89"; // 在流中插入一串數字
 
string strValue;
os >> strValue;
 
string strValue2;
os >> strValue2;
 
// 列印由短劃線分隔的數字
cout << strValue << " - " << strValue2 << endl;

該程式列印:

12345 - 67.89
請注意,>>運算子遍歷字串,每次連續使用>>都會返回流中的下一個可提取值。另一方面,str()返回流的整個值,即使>>已經在流上使用了>>。

字串和數字之間的轉換

因為插入和提取操作符知道如何使用所有基本資料型別,所以我們可以使用它們將字串轉換為數字,反之亦然。

首先,我們來看看將數字轉換為字串:

stringstream os;
 
int nValue = 12345;
double dValue = 67.89;
os << nValue << " " << dValue;
 
string strValue1, strValue2;
os >> strValue1 >> strValue2;
cout << strValue1 << " " << strValue2 << endl;

這個片段列印:

12345 67.89
現在讓我們將數字字串轉換為數字:

stringstream os;
os << "12345 67.89"; //在流中插入一串數字
int nValue;
double dValue;
 
os >> nValue >> dValue;
 
cout << nValue << " " << dValue << endl;

該程式列印:

12345 67.89
清除字串流以供重用

有幾種方法可以清空stringstream的緩衝區。

1)使用帶有空白C風格字串的str()將其設定為空字串:

stringstream os;
os << "Hello ";
 
os.str(""); // 刪除緩衝區
 
os << "World!";
cout << os.str();

2)使用帶有空白std :: string物件的str()將其設定為空字串:

stringstream os;
os << "Hello ";
 
os.str(std::string()); //刪除緩衝區
 
os << "World!";
cout << os.str();

這兩個程式都產生以下結果:

World!
清除字串流時,呼叫clear()函式通常也是個好主意:

stringstream os;
os << "Hello ";
 
os.str(""); //刪除緩衝區
os.clear(); //重置錯誤標誌
 
os << "World!";
cout << os.str();

clear()重置,可能已設定的任何錯誤標誌,並將流返回到ok狀態。我們將在下一課中詳細討論流狀態和錯誤標誌。