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

时间:2019-01-25 22:53:39

标签: c++

这是我的家庭作业之一,在cin while循环之后,我一直遇到段错误,有人可以告诉我我做错了什么吗?我还没有学习地图,所以我不能这样做。我的想法之一是,由于我正在比较向量中的两个字符串元素,因此出现了段错误,正确执行此操作的方法是什么?

#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;
}

1 个答案:

答案 0 :(得分: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;
}