Search code examples
c++vectorpush-back

C++ vector push_back function


So I am pretty new to coding and am having some issues with storing user input into a vector using the push_back function. can some one tell me what I am doing wrong?

  vector<int> user_nums;

     switch(selection){
        case 'P':
        case 'p':
            if(user_nums.empty()){
                cout << "[]- list is empty" << endl;
            }else{
                for(auto nums: user_nums)
                    cout <<"[ " << nums << " ]" << endl;
            }
            break;
        case 'A':
        case 'a':
            int new_num;
            cout << "\nEnter a number you would like to add: ";
            cin >> new_num;
             user_nums.push_back(new_num);
            cout << new_num << " was added" << endl;
            break;

This is in a do while loop. The code executes just fine, the problem is when I prompt the user to add a new number the value does not store in the vector. So when the user makes the selection to print the numbers, the list still shows empty.


Solution

  • So, you're missing the most relevant sections of your code here. You should really be posting a minimal, reproducible example. Often the process of creating one will cause you to find your problem.

    In this case though, it's obvious enough. There's a loop wrapping all this code. The vector is declared inside the loop. That means, at the bottom of the loop the vector will be destroyed, and then as the loop is executed again, a new empty vector will be created.

    The solution is to move the declaration of the vector outside the loop.

    If I've guessed wrong about the structure of the code you haven't shown us, then please follow the guideline I linked to above.