The purpose of this program is to read strings from a .txt file and put all the non-repeating words into a set. I did this by putting all the words into a vector and then attempted to go through it and add only the unique words to the set and deleting the repeating words from the vector. Here is my complete code with the part I am having trouble with at the bottom.
#include <iostream>
#include <fstream>
#include <set>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
int main ()
{
//create data types
set<string> non_duplicate;
vector<string> vectorstring;
vector<string>::iterator it;
ifstream file;
//open file return 1 if can't be opened
file.open ("txt.txt");
if (!file.is_open()) return 1;
//make variable for word
string word;
//take words one at a time from file and add to vector/
while (file >> word)
{
vectorstring.push_back(word);
}
//check vector from repeats and add to set if not
do
{
string temp = vectorstring[0];
vectorstring.erase(vectorstring.begin());
bool duplicate = 0;
check:
if (vectorstring.size() == 0)
{
non_duplicate.insert (temp);
break;
}
it = find(vectorstring.begin(), vectorstring.end(), temp);
if (*it != temp && duplicate != 1)
{
non_duplicate.insert (temp);
}
else if (*it == temp)
{
vectorstring.erase(it);
duplicate = 1;
goto check;
}
} while (!vectorstring.empty());
//output results
cout << "List of non-repeating words: ";
for (auto x = non_duplicate.begin(); x !=non_duplicate.end(); x++)
{
cout << *x << " ";
}
cout << endl;
This is the bit of code causing me problems. Everytime I get towards the last 3ish elements in the vector the find function and "it" do not give me the correct output. For instance if the temp value being searched for is "ben" and the last of these words has been deleted the value of it does not reset and stays "ben" after going through find making it seem as though there is still a value of "ben" when there is not. I'm not sure why this is happening since it works on every value except those near the end?
do
{
string temp = vectorstring[0];
vectorstring.erase(vectorstring.begin());
bool duplicate = 0;
if (vectorstring.size() == 0)
{
non_duplicate.insert (temp);
break;
}
check:
it = find(vectorstring.begin(), vectorstring.end(), temp);
if (*it != temp && duplicate != 1)
{
non_duplicate.insert (temp);
}
else if (*it == temp)
{
vectorstring.erase(it);
duplicate = 1;
goto check;
}
} while (!vectorstring.empty());