对于文件中的每个不同单词,显示该单词在文件中出现的次数
For each distinct word in the file, display a count of the number of times that word appears in the file
这是我的作业之一,在循环之后我不断遇到 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;
}
相关文章:
- 文本文件中的单词链表
- 在指针的帮助下,文本文件中单词的频率
- 我们如何在文本文件中找到C++中的几个单词?
- 是否可以在文本文件中找到最长单词的长度,并在同一个文本文件中读取,只需 1 个 while 循环?
- 按单词搜索文件,然后在C++中打印特定行数
- 如何检查流中文件的下一个单词是否为 alpha?
- 从文件中查找单词并替换到其他文件中
- 该程序将.csv文件中的一系列单词放入数组中,然后随机生成句子.但它不起作用
- 如何逐行从文件中获取单词,并在C++中用分号分隔?
- 如何从文件中读取单词,将它们分配给数组并分析其内容?
- 如何在 c++ 中从文本文件中获取特定单词?
- 我们如何重新制作程序以打开xml文件并在价格单词之后读取百分比值并更改此值
- 从之前添加的批处理文件中删除单词
- C++读取大文件并将其保存到字符串中,然后删除特定的随机单词
- C++ 如何检查哪些单词不在 2 个类似文件中
- 显示文件中具有最小给定元音数的单词
- 简单的二分搜索对我不起作用。我正在尝试从文本文件中搜索单词
- 使用结构数组计算文本文件中单词的出现次数C++
- 包含换行符分隔的单词的文件和C++中这些单词的字符串向量的大小是否相同?
- 将玩家输入与单词文件进行比较