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

时间:2013-04-09 10:50:46

标签: c++ string vector switch-statement push-back

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

这是以下计划:

#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;
}

5 个答案:

答案 0 :(得分:5)

此:

vector<string> journal;

while循环的每次迭代时重新创建,因此当打印元素的代码在新的空vector上运行时。将journal的定义移至while循环之外:

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

push_back()vector的硬编码值如果不想重复添加,也可能需要移出循环。

答案 1 :(得分:1)

向量在循环中声明,因此它们是本地的,并且为循环的每次迭代重新创建。这意味着该计划每次都会忘记自己的过去。在循环之前移动矢量声明,事情会有很大改善!

答案 2 :(得分:0)

在循环之前仅创建一次向量:

vector<string> journal;
while (running) // <- also change this to avoid inf loop
{
 string s("me");
 journal.push_back(s);
 //.. do things with your vector "journal"
}

另外要小心你在循环中做的事情。

答案 3 :(得分:0)

这是因为你的vector变量是在while循环范围内实例化的。这意味着它是在循环的每个回合中新创建的,随着switch语句的case 2:添加的数据都将丢失。

答案 4 :(得分:0)

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

     using namespace std;
 vector<string> journal;//**SHOULD NOT WRITE INSIDE THE LOOP**
 int main()

  {
bool running = true;

while (running = true) 
{


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;

}