c++ - 如何在数组中加载特定文件的所有唯一单词并显示它们 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();
但现在我对如何找到独特的词感到困惑。任何指导。
解决方案
下面的程序显示了如何计算给定文本文件中的所有唯一单词,然后显示每个单词出现的次数:
#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 文件也可以在上面提到的链接中找到。
推荐阅读
- asp.net-mvc - Handle Vue Route on Page Reload from MVC Controller
- azure-devops - CI/CD Deployment Using Azure Devops
- c++ - 在 Mac OS 10.15 中打开 GL 版本 2.1 而不是 4.1
- javascript - 将 Google Apps 脚本数组应用到 HTML 表单自动完成数据列表中
- asp.net-core - 身份服务器 4、Asp.net 身份和
- python - Telegram API:我可以获取频道的历史用户数据吗?
- python - 如何在纸浆优化中限制变量?
- javascript - 按钮更改输入值,但输入显示旧值
- plugins - 用于显示创建日期的网络数据插件
- jquery - 圆形动画汉堡菜单未打开菜单项