I am making a program that loads a wordlist, then uses a function to find anagrams of an input word in the wordlist. I add these words to a vector.
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
int main()
{
vector<string> words;
vector<string> anagrams;
string inputWord;
words=loadWordlist("wordlist.txt");
cout << "Find single-word anagrams for the following word: ";
cin >> inputWord;
anagrams = anagram(inputWord, words);
for (int i=0; i<anagrams.size(); i++)
{
cout << anagrams[i] << endl;
}
return 0;
}
vector<string> loadWordlist(string filename)
{
vector<string> words;
ifstream inFile;
string word;
inFile.open(filename);
if(inFile.is_open())
{
while(getline(inFile,word))
{
if(word.length() > 0)
{
words.push_back(word);
}
}
inFile.close();
}
return words;
}
bool isAnagram(string word1, string word2){
int n1=word1.length();
int n2=word2.length();
if(n1!=n2){
return false;
}
sort(word1.begin(), word1.end());
sort(word2.begin(), word1.end());
for(int i=0; i<n1; i++){
if(word1[i]!=word2[i]){
return false;
}
}
return true;
}
vector<string> anagram(string word, vector<string> wordlist)
{
vector<string> anagramList;
string compareWord;
int size=wordlist.size();
for(int i=0; i<size; i++){
compareWord=wordlist[i];
if(isAnagram(word, compareWord)==true){
anagramList.push_back(compareWord);
}
}
return anagramList;
}
The program is supposed to take an included text file(wordlists.txt) and create a vector of strings using the words from the list. It then uses this list of words and compares each word to a inputted word to check if they are anagrams. If they are anagrams, then the word from the wordlist is then added to the vector anagramList
I dont get a line number when it returns the fault, but I am sure the issue is somewhere in my anagram function. I always have issues with using vectors and trying to access their values, so any help is appreciated.