Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

สตริงสตรีมใน C ++


ที่นี่เราจะเห็นสตรีมสตริงใน C ++ สตรีมสตริงเชื่อมโยงวัตถุสตริงกับสตริง เมื่อใช้สิ่งนี้เราสามารถอ่านจากสตริงราวกับว่ามันเป็นสตรีมเช่น cin

Stringstream มีวิธีการที่แตกต่างกัน เหล่านี้เป็นเหมือนด้านล่าง −

ชัดเจน(): ใช้เพื่อล้างสตรีม

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