Jump to content
  • Advertisement
Sign in to follow this  

Struggling with iterators

This topic is 4338 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm working through the section on iterators in the "C++ Primer" and have encountered the following problem.
#include <iostream>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;

int main()
{
	int entry;
	vector<int> numbers;
	while (cin >> entry);
		numbers.push_back(entry);
	for (vector<int>::iterator index = numbers.begin(); index != numbers.end(); ++index)
		cout << *index << endl;
	return 0;
}

This extremely simply program, when compiled, doesn't do what I want it to. When I input the numbers 1, 2, 3, 4 & 5 then a ^D to signal the end of input the program returns "5" instead of printing each element in the vector. I can get the program to work fine using subscript operators instead of iterators. What am I doing wrong here?

Share this post


Link to post
Share on other sites
Advertisement
Removing the ; afther the while-statement should do the trick.


#include <iostream>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::vector;

int main()
{
int entry;
vector<int> numbers;
while (cin >> entry) // ; removed here
numbers.push_back(entry);
for (vector<int>::iterator index = numbers.begin(); index != numbers.end(); ++index)
cout << *index << endl;
return 0;
}



Share this post


Link to post
Share on other sites
This is why I always brace my braceable (if/while/for/do-while) statements, and put the opening brace on the same line. I stick with either of:


while (foo) { bar; } // note braces used anyway


or


while (foo) {
bar;
baz;
quux;
}


That's just a personal preference, of course; there are certainly reasons to recommend any other popular way of doing it. But I've found this one less error-prone, while also conserving vertical space (that's not a where-did-I-put-that-declaration thing for me, but an aesthetic one) :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!