Search code examples
c++stringvectorswitch-statementpush-back

Having trouble adding an element to a string vector


I'm writing a simple journal like function, however I can't seem to fathom out how to generate a new element of the vector by passing the value the user enters. I am new to programming so the answer might well be obvious :/ I get no errors when I compile the program but the code for adding in a journal entry seems to have no effect. Any ideas?

This is the program below:

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

using namespace std;

int main()

{
    bool running = true;

    while (running = true) 
    {

    vector<string> journal;
    vector<string>::const_iterator iter;
    int count = 1;

    journal.push_back("Day 1. Found some beans.");
    journal.push_back("Must remember not to eat beans");
    journal.push_back("Found some idiot who traded beans for a cow!");

    cout << "Journal Tester.\n\n";


    cout << "1 - View Journal\n2 - Add journal entry\n";
    cout << "3 - Quit\n";
    cout << "\nPlease choose: ";

    string newentry;
    int choice; 
    cin >> choice;
    cout << endl;

    switch (choice)
    {
    case 1:
        for (iter = journal.begin(); iter != journal.end(); ++iter)
    {

        cout << "Entry " << count << ": \n";
        cout << *iter << endl; 
        ++ count;
    }
        count = 1;
        break;

    case 2: 

        cout << "\nYou write: ";
        cin >> newentry; 

        cout << endl << newentry;
        journal.push_back(newentry); 

        break;

    }

    } 

    return 0;
}

Solution

  • This:

    vector<string> journal;
    

    is recreated on each iteration of the while loop so when the code that prints the elements operates on a new empty vector. Move the definition of journal to outside of the while loop:

    vector<string> journal;
    while (running) // Note removed assignment here.
    {
    }
    

    And the hardcoded values that are push_back()ed into the vector may also need to moved outside of the loop if you do not want these repeatedly added.