Entering values to a vector and print it

I can´t get all the values to print and I get a value printed at the first row that isn´t supposed to be printed. Th build should be successful. No errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  #include <iostream>
#include <vector>

using namespace std;

vector<int> myVector;

int main()
{
	cout << "Type in a list of 5 numbers " << endl;

	for (int i = 0; i < 5; i++) 
	{
		int input;
		myVector.push_back(input);
		cin >> input;
	}

	for (int i = 0; i < 5; i++) 
	{
		cout << myVector[i] << endl;
	}

		return 0;
}
I can´t get all the values to print and I get a value printed at the first row that isn´t supposed to be printed


The problem has to deal with you assigning the input into the vector before you are even taking it in.

1
2
3
int input;  // Non initialized so a random number will print first (Undefined behavior)
myVector.push_back(input); // Pushing to vector before getting input from user
cin >> input; // Finally get input. 


This results in undefined behavior on the first storage in the vector. The rest of the numbers you push back into the vector will be the previous loop iteration's input instead. That is why you are getting a wierd number and why not all numbers are showing up (Or seems that way).
Solved it. Thank you :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>

using namespace std;

vector<int> myVector;

int main()
{
	cout << "Type in a list of 5 numbers " << endl;

	int input = 0;

	for (int i = 0; i < 5; i++) 
	{
		cin >> input;
		myVector.push_back(input);
		
	}

	for (int i = 0; i < 5; i++) 
	{
		cout << myVector[i] << endl;
	}

		return 0;
}
Topic archived. No new replies allowed.