C++ 中的字串流


在本文中,我們將瞭解 C++ 中的字串流。字串流將字串物件與字串相關聯。利用這一特性,我們可以像使用 cin 一樣從字串中讀取資料。

字串流有不同的方法。如下所示 −

clear(): 用於清除流

str(): 用於獲取和設定流中存在內容的字串物件

運算子 << : 將一個字串新增到字串流中

運算子 >> : 用於從字串流物件中讀取資料。

我們來看兩個字串流的示例。在第一個程式中,我們將單詞拆分為單獨的字串。

示例

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
   string str("Hello from the dark side");
   string tmp; // A string to store the word on each iteration.
   stringstream str_strm(str);
   vector<string> words; // Create vector to hold our words
   while (str_strm >> tmp) {
      // Provide proper checks here for tmp like if empty
      // Also strip down symbols like !, ., ?, etc.
      // Finally push it.
      words.push_back(tmp);
   }
   for(int i = 0; i<words.size(); i++)
      cout << words[i] << endl;
}

輸出

Hello
from
the
dark
side

在這裡,我們將使用字串流將十進位制轉換為十六進位制。

示例

#include<iostream>
#include<sstream>
using namespace std;
main(){
   int decimal = 61;
   stringstream my_ss;
   my_ss << hex << decimal;
   string res = my_ss.str();
   cout << "The hexadecimal value of 61 is: " << res;
}

輸出

The hexadecimal value of 61 is: 3d

更新於: 2019 年 7 月 30 日

10K+ 瀏覽量

開啟你的 職業之路

完成課程即可獲得認證

開始
廣告