溫馨提示×

istringstream、ostringstream、stringstream類介紹

小云
125
2023-08-24 15:32:44
欄目: 編程語言

istringstream、ostringstream和stringstream類都是C++標準庫中的流類,用于處理字符串。它們都是繼承自基類istringstream、ostringstream和stringstream。

  1. istringstream類:

istringstream類用于從字符串中讀取數據。它主要用于將字符串轉換為其他數據類型,比如將字符串轉換為整數、浮點數等。istringstream對象可以像輸入流一樣從字符串中讀取數據,并且可以通過輸入操作符(>>)進行數據提取。例如:

#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string str = "123 456 789";
std::istringstream iss(str);
int num1, num2, num3;
iss >> num1 >> num2 >> num3;
std::cout << num1 << " " << num2 << " " << num3 << std::endl;
return 0;
}

輸出:

123 456 789
  1. ostringstream類:

ostringstream類用于將數據輸出到字符串中。它主要用于將其他數據類型轉換為字符串。ostringstream對象可以像輸出流一樣使用輸出操作符(<<)將數據寫入到字符串中。例如:

#include <iostream>
#include <sstream>
#include <string>
int main() {
std::ostringstream oss;
int num1 = 123;
float num2 = 3.14;
std::string str = "abc";
oss << num1 << " " << num2 << " " << str;
std::string result = oss.str();
std::cout << result << std::endl;
return 0;
}

輸出:

123 3.14 abc
  1. stringstream類:

stringstream類是istringstream和ostringstream的結合體,既可以從字符串中讀取數據,也可以將數據寫入到字符串中。stringstream對象可以同時用作輸入流和輸出流,可以通過輸入操作符(>>)和輸出操作符(<<)進行數據的讀取和寫入。例如:

#include <iostream>
#include <sstream>
#include <string>
int main() {
std::stringstream ss;
int num1 = 123;
float num2 = 3.14;
std::string str = "abc";
ss << num1 << " " << num2 << " " << str;
int result1;
float result2;
std::string result3;
ss >> result1 >> result2 >> result3;
std::cout << result1 << " " << result2 << " " << result3 << std::endl;
return 0;
}

輸出:

123 3.14 abc

總結:istringstream類用于從字符串中讀取數據,ostringstream類用于將數據寫入到字符串中,stringstream類既可以從字符串中讀取數據,又可以將數據寫入到字符串中。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女