Problem with VS and vector chapter from Stroustrup's book.

Noob here, I've writing the examples from Stroustrup's book "Programming: Principles and Practice Using C++" to my compiler just to practise and try the examples provided, so far so good until now that I can't get anything off of this piece of code, and I can't figure it out, once compiled I just can write endless words without any result. Am I doing anything wrong? Is it supposed to be like this? could it be the compiler? I want to return the results "Number of words" and cout << words[i] << '\n\; but it doesn't do anything.
I'm using:

Microsoft Visual Studio Community 2015
Version 14.0.25431.01 Update 3

this is the code verbatim from the book chapter 4.6.4:



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "std_lib_facilities.h"

// simple dictionary: listed of sorted words

int main()
{

	vector<string> words;
	for (string temp; cin >> temp; )  //read whitespace-separated words     
		words.push_back(temp);	//put into vector
	cout << "Number of words: " << words.size() << '\n';

	sort(words);	//sort the words

	for (int i = 0; i < words.size(); ++i)
		if (i == 0 || words[i - 1] != words[i])	// is this a new word?
			cout << words[i] << "\n";
	

	return 0;


}


thanks!
Last edited on
closed account (SECMoG1T)
you need a condition to exit this loop otherwise it will execute until some error flag is set on the stream

for (string temp; cin >> temp; )

The function std::sort takes a pair of iterators not a container except if the sort function is user defined.

1
2
///sort(words);  would be
sort(words.begin(),words.end());


well from what i see the for loop might not be exactly what you need maybe you could consider a while loop instead.
Last edited on
Works fine for me.
OUTPUT:

Anna Lisa Jenni
^Z
Number of words: 3
Anna
Jenni
Lisa

You need to enter the words and hit return, then hit Ctrl + Z or F6 on windows.

@andy1992
sort is defined in std_lib_facilities.h and takes a container
aaah thank you man! I understand better now.
Is std_lib_facilities.h part of the standard? The std::sort() templates don't mention this signature: http://en.cppreference.com/w/cpp/algorithm/sort
No std_lib_facilities.h is not part of the standard. It's Stroustrup's way to make things for beginners easier.
You can find the code at: http://www.stroustrup.com/Programming/std_lib_facilities.h
Ah! I see, thanks
Topic archived. No new replies allowed.