qq_32090449 2017-11-01 12:46 采纳率: 0%
浏览 874

c++ 读一个几百行的文本文件时运行会出错

当test.txt只有十几行文本时运行正常
当文件有几百行后就会出错

 #include <iostream>
#include <unordered_map>
#include <vector>
#include <cctype>
#include <fstream>
#include <string>
#include <iterator>
#include <sstream>
#include <cstring>
#include <algorithm>
#include <iomanip>
using namespace std;
void count(unordered_map<string, int> &m, int &sum){
    ifstream fin("test.txt");
    string line;
    while(1){
        getline(fin, line);
        if(fin.eof())  break;
        istringstream ss(line);
        string text, word;
        while(1){
            ss >> text;
            if(ss.eof()) break;
            remove_copy_if(text.begin(), text.end(), back_inserter(word), [](const char &c){ return !isalpha(c); });
            for(int i = 0; i < word.size() - 1; ++i){
                char ch1 = toupper(word[i]), ch2 = toupper(word[i + 1]);
                string s({ch1, ch2});
                if(m.find(s) == m.end()) m[s] = 1;
                else                     ++m[s];
                ++sum;
            }
            word.clear();
        }
    }
    fin.close();
}
int main(){
    unordered_map<string, int> alphabet_freq;
    int sum = 1;
    count(alphabet_freq, sum);   //统计频率
    vector<pair<string, double>> v;  // 将关联容器数据存储于顺序容器排序
    for(auto it = alphabet_freq.cbegin(); it != alphabet_freq.cend(); ++it){
        v.push_back(make_pair(it->first, double(it->second) / sum));
    }
    //按second降序
    sort(v.begin(), v.end(), [](const pair<string, double> &lhs, const pair<string, double> &rhs){
        return lhs.second > rhs.second; });
    for(auto it = v.cbegin(); it != v.cend(); ++it){
        if(it->second < 0.01) continue;
        cout << it->first << " : " << it->second <<endl;
    }
    return 0;
}

  • 写回答

1条回答 默认 最新

  • AlbertS 博客专家认证 2017-11-04 03:53
    关注

    你最好把错误也贴出来,直接看代码找问题太浪费时间了

    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配