0

したがって、ベクターの内容を追加、削除、および印刷する必要があるプロジェクトがあります...問題は、プログラムを実行すると、ベクターに追加する文字列を入力する前にプログラムが終了することです。その部分が含まれている関数についてコメントしました。

ありがとう!

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

using namespace std;

void menu();
void addvector(vector<string>& vec);
void subvector(vector<string>& vec);
void vectorsize(const vector<string>& vec);
void printvec(const vector<string>& vec);
void printvec_bw(const vector<string>& vec);

int main()
{
    vector<string> svector;

    menu();

    return 0;
}
//functions definitions

void menu()
{
    vector<string> svector;
    int choice = 0;

        cout << "Thanks for using this program! \n"
             << "Enter 1 to add a string to the vector \n"
             << "Enter 2 to remove the last string from the vector \n"
             << "Enter 3 to print the vector size \n"
             << "Enter 4 to print the contents of the vector \n"
             << "Enter 5 ----------------------------------- backwards \n"
             << "Enter 6 to end the program \n";
        cin >> choice;

        switch(choice)
        {

                case 1:
                    addvector(svector);
                    break;
                case 2:
                    subvector(svector);
                    break;
                case 3:
                    vectorsize(svector);
                    break;
                case 4:
                    printvec(svector);
                    break;
                case 5:
                    printvec_bw(svector);
                    break;
                case 6:
                    exit(1);
                default:
                    cout << "not a valid choice \n";

            // menu is structured so that all other functions are called from it.
        }

}

void addvector(vector<string>& vec)
{
    string line;

     int i = 0;

        cout << "Enter the string please \n";
        getline(cin, line); // doesn't prompt for input!
        vec.push_back(line);    

}

void subvector(vector<string>& vec)
{
    vec.pop_back();
    return;
}

void vectorsize(const vector<string>& vec)
{
    if (vec.empty())
    {
        cout << "vector is empty";
    }
    else
    {
        cout << vec.size() << endl;
    }
    return;
}

void printvec(const vector<string>& vec)
{
    for(int i = 0; i < vec.size(); i++)
    {
        cout << vec[i] << endl;
    }

    return;
}

void printvec_bw(const vector<string>& vec)
{
    for(int i = vec.size(); i > 0; i--)
    {
        cout << vec[i] << endl;
    }

    return;
}
4

2 に答える 2

4

プログラムを実行するときに、番号1を入力して、プログラムに追加することを伝えます。1と入力した後、Enterキーを押すと、入力に改行が挿入され、読み取られるのを待機します。addvector関数で、readlineはその改行を読み取ります。

これは宿題なので、問題を理解した上で、自分で解決策を見つけたほうがよいでしょう。

于 2010-05-11T02:53:35.490 に答える
1

>>とのgetline呼び出しはお互いにうまくいっていません。'>>'は、を飲み込まないため\n、で空の文字列が生成されgetlineます。

于 2010-05-11T02:54:55.483 に答える