两个注意点:
1.统计的是不同的单词数,而不是总的单词数(用set或者map可以解决)
2.注意各种空格的位置,开头,结尾,中间多个连续,都需要考虑(可以看看我的代码)
#include <iostream>
#include <stdexcept>
#include <string>
#include <unordered_set>
using namespace std;
int main() {
string s = "#";
string ans;
while (getline(cin, ans) && ans != s) {
long num = 0;
unordered_set<string> st;
string temp = "";
int n = ans.length();
for (int i = 0; i < n; i++) {
if (ans[i] == ' ' && temp != "") {
st.insert(temp);
temp = "";
} else if (ans[i] != ' ')
temp += ans[i];
}
if (ans[n - 1] != ' ')
st.insert(temp);
cout << st.size() << endl;
}
return 0;
}