1

CreateList 関数は次のことを行う必要があります。 1. ユーザーに食料品店の名前を尋ねます。2. ユーザーが「完了」と入力するまで、この食料品店のアイテムのリストを入力するようにユーザーに依頼します。3. 入力された文字列のベクトルに項目を追加します。4. 表示: 「食料品店名リストに商品を追加しました。」ここで、「item」は入力したアイテム、「grocery store name」は上記のステップ 1 で入力した名前です。

void CreateList()
{   
    string store;
    string item;
    int count = 0;
    cout<<"What is the grocery store name"<<endl;
    cin>>store;
    vector<string> store;
    cout<<"Enter a list of items for this grocery store one at a time. When you are done, type done."<<endl;
    cin>>item;
    store[count] = item; //error saying no conversion?
    count++;
    cout<<"Added "<<item<<"to "<<store<<"list"<<endl;
    bool finished=true;
    while (finished = true)
    {
        cout<<"Enter a list of items for this grocery store one at a time. When you are done, type done."<<endl;
        cin>>item;

        if (item == "done")
        break;

        store[count] = item; //error saying no conversion?
        count++;
        cout<<"Added "<<item<<"to "<<store<<"list"<<endl;
}


}

私の関数についていくつか質問がありましたが、変換エラーがどこから来ているのかわからず、これを do while ループに実装できますか? 答えはできるだけシンプルにしてください。これは、Python からの移行中に C++ で初めて試みたものです。御時間ありがとうございます。

4

4 に答える 4

0

store と呼ばれる 2 つの変数があります。1 つは文字列で、もう 1 つは文字列のベクトルです。次に、この 2 つを混同しているように見えます。これは、文字列ではなく文字itemstore[count]表すに割り当て、後で製品のリストを単一の文字列と見なして出力しようとします。

変数名を意味のあるものにすることで、コードを修正する必要があります。

void CreateList()
{   
    std::string storeName;
    std::cout << "What is the grocery store name" << std::endl;
    std::cin >> storeName;

    std::cout << "Enter a list of items for this grocery store one at a time. When you are done, type done." << std::endl;

    std::vector<std::string> products;
    while (true)
    {
        std::string product;
        std::cin >> product;

        if (product == "done")
            break;

        products.push_back(product);

        std::cout << "Added " << product << " to " << storeName << " list" << std::endl;
    }
}

C++ に継承された C プログラミングのアーティファクトがあり、1 つの変数を同じ名前の別の変数で「シャドウ」できます。

#include <iostream>

int i = 20;

int main() {
    int i = 10;
    for (int i = 0; i < 5; ++i) {
        std::cout << "loop i = " << i << std::endl;
    }
    std::cout << "i = " << i << std::endl;
}

ライブデモ: http://ideone.com/eKayzN

于 2013-11-01T03:29:43.100 に答える