首页 > 解决方案 > 如何在数组中加载特定文件的所有唯一单词并显示它们 C++

问题描述

停留在如何在文件中找到唯一单词的问题上,我所做的就是加载所有单词并存储在如下数组中:

char *arr=new char[100];
char ch;
fstream my_file("name.txt");
if (!my_file) {
    cout << "No such file";
}
else {
    while(my_file.eof()==0){
        my_file.get(ch);
        arr[i]=ch;
        i++;
    }
  }
   for(int j=0;j<i;j++){
    cout<<arr[j];
   }
   my_file.close();

但现在我对如何找到独特的词感到困惑。任何指导。

标签: c++arraysfile-handling

解决方案


下面的程序显示了如何计算给定文本文件中的所有唯一单词,然后显示每个单词出现的次数:

#include <iostream>
#include <map>
#include <sstream>
#include<fstream>
int main() {
    std::string line, word;
   //this map maps the std::string to their respective count
    std::map<std::string, int> wordCount;
    
    std::ifstream inFile("input.txt");
    
    
    if(inFile)
    {
        while(getline(inFile, line, '\n'))        
        {
            
            std::istringstream ss(line);
            
            while(ss >> word)
            {
                //std::cout<<"word:"<<word<<std::endl;
            wordCount[word]++;
            }      
        }    
    }
    
    else 
    {
        std::cout<<"file cannot be opened"<<std::endl;
    }
    
    inFile.close();
    std::cout<<"Total unique words are: "<<wordCount.size()<<std::endl;
    for(std::pair<std::string, int> pairElement: wordCount)
    {
        std::cout << pairElement.first <<"-" << pairElement.second<<std::endl;
    }
    return 0;
}

上述程序的输出可以在这里看到。

请注意,您不需要数组,因为std::map如上所示就足够了。input.txt 文件也可以在上面提到的链接中找到。


推荐阅读