You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

统计文本文件单词频次的C++程序编译正常但无输出,求排查

问题分析与代码修复

让我帮你排查程序无输出的问题,同时优化代码以更好满足任务要求:

1. 导致无输出的核心问题

你的printReport函数里循环条件写反了!

for(int i = 0; i > words.size(); i++){

这里的i > words.size()永远不成立(初始i是0,words.size()最小是0),循环根本不会执行,自然看不到任何输出。把条件改成i < words.size()就能正常打印统计结果了。

2. 潜在的编译/依赖问题

代码里用到了transform和find函数,这两个属于<algorithm>头文件,但你限定只能用iostream、fstream、string、vector库。为了不超出依赖范围,我们可以修改逻辑,去掉对<algorithm>的依赖:

  • 把isFound函数改成同时返回是否存在和对应的索引,避免用find
  • 手动实现字符串转小写的逻辑,不用transform

3. 优化后的完整代码

#include <iostream>
#include <fstream> 
#include <string>
#include <vector>
using namespace std;

// 同时检查单词是否存在,并返回其索引(不存在则返回-1)
int findWordIndex(const vector<string>& v, const string& word){
    for(int i = 0; i < v.size(); i++){
        if (v[i] == word) {
            return i;
        }
    }
    return -1;
}

// 手动将字符串转为小写(避免依赖algorithm)
void toLowerCase(string& text){
    for(char& c : text){
        if(c >= 'A' && c <= 'Z'){
            c += 32; // ASCII码转换,大写转小写
        }
    }
}
    
void printReport(const vector<string>& words, const vector<int>& count){
    // 修正循环条件
    for(int i = 0; i < words.size(); i++){
        cout << words[i] << ":" << count[i] << endl;
    }
}
    

int main(){
    
    vector<string> words;
    vector<int> count;

    string text;
    ifstream myFile ("data.txt");

    // 先检查文件是否成功打开
    if(!myFile.is_open()){
        cout << "无法打开data.txt文件!" << endl;
        return 1;
    }

    while(myFile >> text){
        // 转小写
        toLowerCase(text);

        int index = findWordIndex(words, text);
        if(index == -1){
            words.push_back(text);
            count.push_back(1);
        } else {
            count[index]++;
        }
    }

    myFile.close();

    printReport(words,count);

    return 0;
}    

额外优化点说明

  • 添加了文件打开失败的判断:如果data.txt不存在或者无法读取,程序会提示错误,避免默默无输出的情况
  • 把函数参数改成const &引用,避免不必要的拷贝,提升效率
  • 合并了查找和索引获取的逻辑,减少一次vector遍历

内容的提问来源于stack exchange,提问作者Milkhead5

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 10:31:14