說我有問題計數詞彙出現的是,我不完全知道如何重置我的字數。我創建了一個單詞搜索,但是當我計算出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 <的std :: string,int>的'來解決。 –
我認爲你需要設置'在'for'循環的每次迭代的開始數= 0'和'POS = 0'。基本上,你可以將這兩個聲明**移動到**循環中。 –