проблема, с которой я сталкиваюсь, заключается в том, что я не совсем уверен, как сбросить количество слов. Я создал поиск по словам, но когда я подсчитаю количество вхождений 10 разных слов, он останется тем же числом из первого слова, которое он считает. Я считаю, что проблема у меня, где я использую for
петлюПроблема со входом счетного слова для нескольких слов
Выход
boy appeared 3 times
Snape appeared 3 times
Dumbledore appeared 3 times
he appeared 3 times
her appeared 3 times
the appeared 3 times
it appeared 3 times
is appeared 3 times
will appeared 3 times
all appeared 3 times
Что это должно выглядеть
boy appeared 3 times
Snape appeared 7 times
Dumbledore appeared 4 times
he appeared 27 times
her appeared 4 times
the appeared 13 times
it appeared 6 times
is appeared 12 times
will appeared 2 times
all appeared 3 times
Читая мои коды Я уверен, что я имею сделал его более сложным, чем он есть. Я был бы признателен за любые советы и исправления, которые я сделал.
Полный код
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
// Main Function
int main()
{
// Declaration
std::string list, passage, word[10];
std::ifstream listFile("WordList.txt", std::ios::in);
std::ifstream passageFile("HarryPotterPassage.txt", std::ios::in);
std::vector<std::string> vec_wordList, vec_passage;
/* Read a file that contains a list of 10 words */
if (listFile.is_open())
{
// Store text file in a vector
while (listFile)
{
listFile >> list;
vec_wordList.push_back(list);
}
// Assign vector to individual strings
for (int i = 0; i < 10; i++)
{
word[i] = vec_wordList[i];
}
// Close file
listFile.close();
}
else
std::cout << "No file found.\n";
/* Read another file containing a paragraph */
if (passageFile.is_open())
{
while (passageFile)
{
// Store text file in a string
std::getline(passageFile, passage);
}
// Close file
passageFile.close();
}
else
std::cout << "No file found.\n";
//std::cout << passage << '\n';
/* Count the number of words from the first file
from the second file that contains the paragraph */
size_t count = 0;
std::string::size_type pos = 0;
for (int i = 0; i < 10; i++)
{
while ((pos = passage.find(word[i], pos)) != std::string::npos)
{
count++;
pos += word[i].size();
}
std::cout << word[i] << " appeared " << count << " many times\n";
}
system("pause");
return 0;
}
Спасибо заранее.
Было бы легче решить с помощью 'std :: unoredered_map'. –
Я думаю, что вам нужно установить 'count = 0' и' pos = 0' в начале каждой итерации цикла 'for'. В принципе, вы можете просто переместить эти два объявления ** в ** этот цикл. –