这个题目有一点点坑。刚开始我是直接按照空格的数目来算单词的数目,就直接判错了。考虑不太周到。有可能有以下的情况:(用-代表空格)
“------abc-ef” (即有先导空格)“abc--------ef” (两个单词间差了好几个空格)“abc-ef------”(结尾有好多空格)如果直接考虑的话会比较麻烦,于是借鉴了其他人的代码。深有收获。 依靠cin在获取输入时不会接受空格,从而方便的解决问题。
#include <iostream> #include <stdio.h> #include <string.h> #include <set> #include <sstream> using namespace std; int main() { string str1,str2; while(getline(cin,str1)) { if(str1 == "#") break; istringstream stream(str1); set<string>Set;//定义一个集合 while(stream>>str2) { Set.insert(str2); } cout<<Set.size()<<endl; } return 0; } 看来stream流和string都得学会啊。 先吸取一行,再读每一行的单词。而只用C的话,虽然可以直接用fgets()拿到一行的数据,但接下来读取单个单词时不太方便实现。所以还是用stream流方便许多。