Program getting hung up on For Loop

Hello, this program is from Principles and Practice Using C++ 2nd Ed. by BS on page 123. The program is supposed to accept a list of space-separated words and then print them out alphabetically. However, it gets stuck in the first for-loop. Any insight is appreciated, thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#include "std_lib_facilities.h"
using namespace std;

int main()
{
	vector <string> words;
	for (string temp; cin >> temp;)
		words.push_back(temp);

	cout << "Number of words: " << words.size() << '\n';
	
	sort(words);

	for (int i = 0; i < words.size(); ++i)
		if (i == 0 || words[i - 1] != words[i])
			cout << words[i] << "\n";

	keep_window_open();
	return 0;
}
closed account (2LzbRXSz)
There's no condition to exit your loop. It just keeps going. Maybe add something like
1
2
3
4
if (temp == ".")
{
   break;
}

?

Also, sort should be
sort(words.begin(), words.end());
Last edited on
Got you...

I reread through the book and it actually does say that in order to break the loop, he expects you to do Ctrl+Z for windows. Not very user friendly of course but it works. Yours works too.

FYI, the sort function is overloaded and defined in the "std_lib_facilities.h" Hope my use of terminology is proper.

Thanks for you help.
closed account (2LzbRXSz)
Huh... I wonder why they'd tell you to code it like that?

Ah, I didn't realize. Sorry about the mistake on my part.
Topic archived. No new replies allowed.