使用非标准分隔符

名称:使用非标准分隔符
功能:当输入以指定字符(:;,.等)分隔的字符串时,可以把这些指定字符(:;,.等)作为“空白符”处理,这样可以输出以空白符(空格、换行等)和指定字符为分隔的单词。例如:输入:as planned,the guests arrived;then, 则输出arrived as guests planned the then
来源:C++程序设计原理与实践11.7
时间:2017.8.16

#include"std_lib_facilities.h"
class Punct_stream {
public:
    Punct_stream(istream& is):source{is},sensitive{true}{}
    void whitespace(const string& s) { white = s; }
    void add_white(char c) { white += c; }
    bool is_whitespace(char c);
    void case_sensitive(bool b) { sensitive = b; }
    bool is_case_sensitive() { return sensitive; }
    Punct_stream& operator>>(string& s);
    operator bool() {// return source.good(); }  //类型转换函数
        return !(source.fail() || source.bad()|| source.eof()) && source.good(); }
private:
    istream& source;
    istringstream buffer;
    string white;
    bool sensitive;
};
bool Punct_stream::is_whitespace(char c)
{
    for (char w : white)
        if (c == w) return true;
    return false;
}
Punct_stream& Punct_stream::operator>>(string& s)
{
    /*buffer中存有字符,读操作buffer>>s就可以进行,s就会收到“空白符”分隔的单
    词,就不进入循环体。当buffer>>s失败时,也就是!(buffer >> s)为真时,我们必
    须利用source中的内容将buffer重新填满*/
    while (!(buffer >> s)) {   
        if (buffer.bad() || !source.good()) return *this;
        buffer.clear();

        string line;
        getline(source, line);       //从source中读入一行

        for (char& ch : line)
            if (is_whitespace(ch))
                ch = ' ';
            else if (!sensitive) ch = tolower(ch);
        buffer.str(line);            //将字符串line放入流buffer中
        cout << line << endl;
    }
    return *this;
}
int main()
{
    Punct_stream ps{ cin };
    ps.whitespace(";:,.?!()\"{}<>/&$@#%^*|~");
    ps.case_sensitive(false);

    cout << "please enter words\n";
    vector<string>vs;
    for (string word; bool l=(ps >> word);)
    {
        vs.push_back(word);
    }
    sort(vs.begin(), vs.end());
    for (int i = 0; i < vs.size(); ++i) 
    {
        if (i == 0 || vs[i] != vs[i - 1]) cout << vs[i] << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值