c++

c++中streamstring的扩展与定制

小樊
82
2024-09-13 01:56:32
栏目: 编程语言

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

  1. 自定义分隔符

    如果你想要使用自定义分隔符来分割字符串,可以创建一个自定义的输入流类,重载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;
    }
    
  2. 格式化输出

    如果你想要格式化std::stringstream的输出,可以使用std::setwstd::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;
    }
    
  3. 自定义转换

    如果你想要将自定义类型转换为字符串或从字符串转换为自定义类型,可以重载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以满足特定需求。你可以根据自己的需求进一步扩展和定制这个类。

0
看了该问题的人还看了