对于文件中的每个不同单词,显示该单词在文件中出现的次数

For each distinct word in the file, display a count of the number of times that word appears in the file

本文关键字:单词 文件 显示 于文件      更新时间:2023-10-16

这是我的作业之一,在循环之后我不断遇到 seg 错误,谁能说出我做错了什么?我还没有学过地图,所以我不能那样做。我的一个想法是它进入了 seg 错误,因为我正在比较向量中的两个字符串元素,有什么方法可以正确地做到这一点?

#include <chrono>
#include <climits>
#include <cfloat>
#include <limits>
#include <cassert>
#include <exception>
#include <cctype>
#include <string>
#include <cmath>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <regex>
#include <vector>
using namespace std;
int main()
{
        vector<string> word_input;
        vector<int> word_count;
        string word;
        string fileName;
        ifstream inputFile;
        cout << "Enter file name: ";
        getline(cin,fileName);
        inputFile.open(fileName);
        while (inputFile.fail())
        {
                cout << "Can't open the file" << endl;
                exit(1);
        }
        cout << "File opened successfully n";
        while (inputFile >> word)
        {
                if (word != word_input.back())
                {
                        word_input.push_back(word);
                        word_count.push_back(1);
                }
                else
                {
                        word_count.push_back( word_count.back() + 1);
                }
        }
        int count =word_count.back();
        // Compare the input words
        // and output the times of every word compared only with all the words
        for (int i = 0; i != count; ++i)
        {
            int time = 0;
            for (int j = 0; j != count; ++j)
                {
                    if (word_input[i] == word_input[j])
                        ++time;
                }
            std::cout << "The time of "
                 << word_input[i]
                 << " is: "
                 << time
                 << endl;
        }
        inputFile.close();
        return 0;
}

您使用的策略充满了问题。一种更简单的方法是使用 std::map<std::string, int> .

int main()
{
   std::map<std::string, int> wordCount;
   string word;
   string fileName;
   ifstream inputFile;
   cout << "Enter file name: ";
   getline(cin,fileName);
   inputFile.open(fileName);
   if (inputFile.fail())
   {
      cout << "Can't open the file" << endl;
      exit(1);
   }
   cout << "File opened successfully n";
   while (inputFile >> word)
   {
      // --------------------------------------------------------------
      // This is all you need to keep track of the count of the words
      // --------------------------------------------------------------
      wordCount[word]++;
   }
   for ( auto const& item : wordCount )
   {
      std::cout << "The time of "
         << item.first
         << " is: "
         << item.second
         << std::endl;
   }
   inputFile.close();
   return 0;
}