无法将元素添加到字符串向量

Isk*_*des -1 c++ string vector push-back switch-statement

我正在编写一个类似函数的简单日志,但是我似乎无法通过传递用户输入的值来了解如何生成向量的新元素.我是编程的新手,所以答案可能很明显:/我编译程序时没有错误,但添加日记条目的代码似乎没有任何效果.有任何想法吗?

这是以下程序:

#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;
}
Run Code Online (Sandbox Code Playgroud)

hmj*_*mjd 5

这个:

vector<string> journal;
Run Code Online (Sandbox Code Playgroud)

while循环的每次迭代中重新创建,以便打印元素的代码在新的空操作​​时运行vector.将定义journal移到while循环外部:

vector<string> journal;
while (running) // Note removed assignment here.
{
}
Run Code Online (Sandbox Code Playgroud)

如果你不想重复添加这些,那么push_back()编入的硬编码值也vector可能需要移出循环.