在C++中,std::stringstream
是一個非常有用的類,它允許你將字符串視為流對象進(jìn)行操作
自定義分隔符:
如果你想要使用自定義分隔符來分割字符串,可以創(chuàng)建一個自定義的輸入流類,重載operator>>
來實(shí)現(xiàn)。
#include<iostream>
#include <sstream>
#include<vector>
#include<string>
class CustomStringStream : public std::istringstream {
public:
CustomStringStream(const std::string& str, char delimiter)
: std::istringstream(str), delimiter_(delimiter) {}
std::istream& operator>>(std::string& token) override {
getline(token, delimiter_);
return *this;
}
private:
char delimiter_;
};
int main() {
std::string input = "hello,world,how,are,you";
CustomStringStream css(input, ',');
std::vector<std::string> tokens;
std::string token;
while (css >> token) {
tokens.push_back(token);
}
for (const auto& t : tokens) {
std::cout << t << std::endl;
}
return 0;
}
格式化輸出:
如果你想要格式化std::stringstream
的輸出,可以使用std::setw
、std::setprecision
等I/O操縱符。
#include<iostream>
#include <iomanip>
#include <sstream>
int main() {
std::stringstream ss;
ss<< std::fixed<< std::setprecision(2) << 3.14159;
std::cout << ss.str()<< std::endl; // 輸出 "3.14"
return 0;
}
自定義轉(zhuǎn)換:
如果你想要將自定義類型轉(zhuǎn)換為字符串或從字符串轉(zhuǎn)換為自定義類型,可以重載operator<<
和operator>>
。
#include<iostream>
#include <sstream>
class Point {
public:
Point(int x, int y) : x_(x), y_(y) {}
friend std::ostream& operator<<(std::ostream& os, const Point& p);
friend std::istream& operator>>(std::istream& is, Point& p);
private:
int x_, y_;
};
std::ostream& operator<<(std::ostream& os, const Point& p) {
os << "(" << p.x_<< "," << p.y_ << ")";
return os;
}
std::istream& operator>>(std::istream& is, Point& p) {
char c;
is >> c >> p.x_ >> c >> p.y_ >> c;
return is;
}
int main() {
Point p1(3, 4);
std::stringstream ss;
ss << p1;
std::cout << ss.str()<< std::endl; // 輸出 "(3,4)"
Point p2;
ss.seekg(0);
ss >> p2;
std::cout << p2 << std::endl; // 輸出 "(3,4)"
return 0;
}
這些示例展示了如何擴(kuò)展和定制std::stringstream
以滿足特定需求。你可以根據(jù)自己的需求進(jìn)一步擴(kuò)展和定制這個類。