如何修改C++程序实现仅统计文件中单词"Ball"的出现次数?
解决统计特定单词"Ball"出现次数的问题
问题根源
你的程序当前统计所有单词的原因有两个:
- 循环内错误地先给
word赋值"Ball",随后ss >> word会覆盖这个值,读取文件中的任意单词,之后无条件累加计数,导致所有单词都被统计。 - 文件中的单词附带标点(比如
Ball,),直接和纯字符串"Ball"比较会不匹配,就算你之前尝试判断,也会漏掉这些带标点的目标单词。
修正后的代码
#include <iostream> #include <fstream> #include <string> #include <sstream> #include <algorithm> #include <cctype> using namespace std; int main() { ifstream file("Programming.txt"); if(file.is_open()) { string line; int ballCount = 0; const string targetWord = "Ball"; // 明确目标单词 while(getline(file, line)) { stringstream ss(line); string word; while(ss >> word) { // 移除单词中所有标点符号 word.erase(remove_if(word.begin(), word.end(), [](char c) { return ispunct(static_cast<unsigned char>(c)); }), word.end()); // 仅当单词匹配目标时累加计数 if(word == targetWord) { ballCount++; } } } file.close(); cout << "Ball occurred " << ballCount << " times"; } else { cerr << "File is closed!"; } }
关键修改说明
- 单独定义目标单词:将
targetWord作为常量单独定义,避免循环中被读取的单词覆盖。 - 处理标点符号:使用
remove_if结合erase,移除单词中的所有标点字符,确保Ball,这类带标点的单词能被正确识别为"Ball"。 - 条件计数:仅当处理后的单词与目标单词完全匹配时,才增加计数,实现精准统计。
简化替代方案(仅处理末尾标点)
如果你的文件只有末尾带标点的情况,也可以用更简单的方式处理:
// 替换掉上面的标点处理部分 size_t lastValidPos = word.find_last_not_of(",.!?;"); if(lastValidPos != string::npos) { word = word.substr(0, lastValidPos + 1); }
内容的提问来源于stack exchange,提问作者rod
相关产品推荐
相关产品推荐

