Requesting help with simple loop problem

I'm trying to have a while loop that reads integers into a vector, as long as cin.good(). The problem im having is the vector always ends up with a size() of 1 more than I expect. Here is the code:
1
2
3
4
5
6
7
8
int integer;
vector<int> integers;
while (cin.good())
	{
		cout << "Enter an integer\n";
		cin >> integer;
		integers.push_back(integer);
	}


If my input to this loop was, for example: 1 2 3 |(to terminate the loop)
Then integers.size() = 4, when i would expect it to only be size of 3.

If i loop through the vector and output each value in the vector, I get this:
1 2 3 3. Can anyone help me understand what is going on?
I suspect you are still doing the push back even on the exiting value and using the last actual interger entered.

I used the following and it gave me size of 3 instead of 4.
1
2
3
4
5
6
7
8
9
10
11
12
13
{
  int integer;
  vector<int> integers;
  do
	{
		cout << "Enter an integer\n";
		cin >> integer;
		if (cin.good()) integers.push_back(integer);
	} while (cin.good());

  cout << integers.size() << endl;
}
Thanks you for the response. Adding the if statement before the push_back statement worked.

I'm still a little confused. When using a while loop, does the loop break immediately when the while loop condition becomes false, or will it continue until the end of the block, and just not loop again?
Last edited on
It continues to the end of the loop regardless.

Your code, with the while on top, would still work too.
In your code the push_back is executed regardless if it was an interger or not. It only exit the loop once the loop tries to start over again.

I'm also new to C++. I believe there is a BREAK statement that could have been used to exit the loop from within it.
1
2
3
4
5
6
7
8
9
    int integer;
    vector<int> integers;
    
    cout << "Enter an integer\n";
    while (cin >> integer)
    {
        integers.push_back(integer);
        cout << "Enter an integer\n";
    }

The problem with the original code, as you no doubt realise by now, is there was no test of success or failure in betwen the user input and the push_back().

Placing the actual input statement in the while condition means that whatever is contained in the body of the loop will only be executed after a successful input.
Last edited on
Yes, with a little tinkering I realized that I didn't fully understand while loops. I was under the false impression that they would break immediately when the condition became false. Thanks for helping to clear up my confusion.
Topic archived. No new replies allowed.