Alphabetical Order Using a Vector

I was attempting to build a program that would read a string of words that were entered using a vector and put them in alphabetical order without repeating any words. The program repeats the words depending on how many elements the vector has though. I'm not sure why this is? Any help would be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 //alphabetical order
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open(){char ch; cin>>ch;}
int main() //main function
{
    vector<string>words; //empty vector
    string temp;
    while (cin>>temp){ //read word
        words.push_back(temp);
    sort(words.begin(),words.end()); //sort words
    for (int i=0; i<words.size(); ++i) //arrange words
        if (i==0||words[i-1]!=words[i]) //new word?
            cout<<words[i]<<'\n';
    }
    keep_window_open();
    return 0;
}


Example: if I input "boy girl boy was"
I get: boy, boy, girl, boy, girl, boy, girl, was
Do you see where your while loop ends? Hint it is not on line 14
I know that one-liners may or may not have curly braces surrounding them, but I always put them anyways to avoid strange errors like this.
Last edited on
Topic archived. No new replies allowed.