名称:使用非标准分隔符
功能:当输入以指定字符(:;,.等)分隔的字符串时,可以把这些指定字符(:;,.等)作为“空白符”处理,这样可以输出以空白符(空格、换行等)和指定字符为分隔的单词。例如:输入: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;
}