本文主要是介绍使用非标准分隔符,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
名称:使用非标准分隔符
功能:当输入以指定字符(:;,.等)分隔的字符串时,可以把这些指定字符(:;,.等)作为“空白符”处理,这样可以输出以空白符(空格、换行等)和指定字符为分隔的单词。例如:输入: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;
}
这篇关于使用非标准分隔符的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!