-1

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

这是下面的程序:

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

5 回答 5

5

这:

vector<string> journal;

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

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

如果您不希望重复添加这些硬编码值,则push_back()可能vector还需要将它们移出循环。

于 2013-04-09T10:53:43.900 回答
1

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

于 2013-04-09T10:55:20.003 回答
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"
}

还要小心你在循环中所做的事情。

于 2013-04-09T10:56:01.887 回答
0

这是因为您的向量变量是在while循环范围内实例化的。这意味着它在循环的每一轮中都是新创建的,与case 2:switch 语句一起添加的数据会丢失。

于 2013-04-09T10:58:54.510 回答
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;

}

于 2013-04-09T11:19:56.387 回答