输入英文单词,统计每个单词的出现次数c++
时间: 2023-12-09 14:04:09 浏览: 55
以下是一个简单的 C++ 代码,可以输入一段英文文本并统计每个单词的出现次数:
```cpp
#include <iostream>
#include <string>
#include <map>
#include <sstream>
using namespace std;
int main() {
string text;
getline(cin, text); // 输入一行文本
// 将文本中的所有非字母字符替换为空格
for (char& c : text) {
if (!isalpha(c)) {
c = ' ';
}
}
// 统计每个单词的出现次数
map<string, int> word_count;
stringstream ss(text);
string word;
while (ss >> word) {
++word_count[word];
}
// 输出结果
for (const auto& p : word_count) {
cout << p.first << ": " << p.second << endl;
}
return 0;
}
```
这个程序首先读入一行文本,然后将其中所有非字母字符替换为空格,以便将文本划分为单词。然后使用一个 `map<string, int>` 来统计每个单词出现的次数,最后输出结果。