wordcount c++
时间: 2023-10-10 19:11:54 浏览: 54
以下是一个简单的 C++ 代码,可以实现对一个文本文件中的单词进行计数:
```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
int main()
{
// 打开文件
ifstream file("filename.txt");
if (!file.is_open()) {
cout << "无法打开文件" << endl;
return 1;
}
string word;
int count = 0;
while (file >> word) {
// 将单词转换为小写字母
transform(word.begin(), word.end(), word.begin(),
[](unsigned char c) { return tolower(c); });
// 去除标点符号
word.erase(remove_if(word.begin(), word.end(), [](unsigned char c) {
return ispunct(c);
}), word.end());
if (!word.empty()) {
++count;
}
}
cout << "单词数:" << count << endl;
return 0;
}
```
这个程序打开一个名为 "filename.txt" 的文本文件,读取其中的单词,并统计单词的数量。在读取单词之前,程序会将单词转换为小写字母,并去除标点符号。最后,程序输出单词的数量。