Jez Bayliss Jez Bayliss - 11 months ago 52
C++ Question

Struggling with creating a function that stores user input to any chosen vector (using c++)

This is what I have so far...

#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<int> list1;
vector<int> list2;

void listAdd(int n, vector<int>v) {
while (n != 0) {
cin >> n;

void printList(vector<int>v) {
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
cout << endl;

int main() {
int nInput;

cout << "Please enter numbers for list1... (end with a '0') " << endl;
cin >> nInput;
listAdd(nInput, list1);
return 0;

I basically want all numbers entered by the user (until they enter a 0) to be stored in the vector called list1. Then later i can call the same function to add numbers to another vector...

Help really appreciated :)

Answer Source

you need to pass the vectors by reference

void listAdd(int n, vector<int>& v);

void printList(vector<int>& v);