阅读量:82
在C++中,std::stringstream是一个非常有用的类,它允许你将字符串视为流对象进行操作
-
自定义分隔符:
如果你想要使用自定义分隔符来分割字符串,可以创建一个自定义的输入流类,重载
operator>>来实现。#include#include #include #include 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 tokens; std::string token; while (css >> token) { tokens.push_back(token); } for (const auto& t : tokens) { std::cout << t class="hljs-keyword">return 0; } -
格式化输出:
如果你想要格式化
std::stringstream的输出,可以使用std::setw、std::setprecision等I/O操纵符。#include#include #include int main() { std::stringstream ss; ss<< std class="hljs-built_in">setprecision(2) << 3.14159; std::cout << ss class="hljs-built_in">str()<< std class="hljs-comment">// 输出 "3.14" return 0; } -
自定义转换:
如果你想要将自定义类型转换为字符串或从字符串转换为自定义类型,可以重载
operator<<和operator>>。#include#include 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 class="hljs-string">"," << p class="hljs-string">")"; 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 class="hljs-built_in">str()<< std class="hljs-comment">// 输出 "(3,4)" Point p2; ss.seekg(0); ss >> p2; std::cout << p2 class="hljs-comment">// 输出 "(3,4)" return 0; }
这些示例展示了如何扩展和定制std::stringstream以满足特定需求。你可以根据自己的需求进一步扩展和定制这个类。