c++中streamstring的扩展与定制

   2024-09-30 2360
核心提示:在C++中,std::stringstream是一个非常有用的类,它允许你将字符串视为流对象进行操作自定义分隔符:如果你想要使用自定义分隔符

在C++中,std::stringstream是一个非常有用的类,它允许你将字符串视为流对象进行操作

自定义分隔符:

如果你想要使用自定义分隔符来分割字符串,可以创建一个自定义的输入流类,重载operator>>来实现。

#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;}

自定义转换:

如果你想要将自定义类型转换为字符串或从字符串转换为自定义类型,可以重载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;}

这些示例展示了如何扩展和定制std::stringstream以满足特定需求。你可以根据自己的需求进一步扩展和定制这个类。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号