2017-11-13 6 views
-4

配列を使用していくつかのコードを処理していますが、配列内の変数の "可変サイズのオブジェクトは初期化できません"というエラーが表示されます。ここにエラーがある私のコードの一部です。変数の初期化エラーC++

int main(){ 
int x = 0; 
int y = 0; 
int items[x][y] = {}; //Here is where I get the error 
for(string food; cin >> food; x++) 
{ 
    items[x] = food; 
    if(food == "done") 
     cout << "Thank you for inputting.\n"; 
} 
for(double price; cin >>price; y++) 
{ 
    items[y] = price; 
    if(price == 0) 
    { 
     double total; 
     total += price; 
    } 
} 

助けていただければ幸いです。ありがとう!

+3

4事柄:1.配列サイズ初期化子変数 'const'してください。 2.サイズ「0」の配列を初期化することはできません。3.配列サイズは、「x」または「y」をインクリメントするにつれて_magically_増加しません。 4. 'std :: vector >'と 'push_back()'を使って動的に成長させます。 – user0042

+5

乱数ジェネレータを使用してこのコードを書いたようです。すべての行が間違っています。推測ではなくC++の本を読んでください。 –

+0

また、可変長配列は固定で非標準であり、代わりに 'std :: vector >'と考えてください。 – George

答えて

1

あなたコード

int x = 0; 
int y = 0; 
int items[x][y] = {}; 

C++標準ではなく、単に特定の拡張でサポートされていない可変長配列itemsを定義します。これを克服するには、xyconstと明示しなければなりません(値> 0、明らかに)。

しかし、私は間違ったデータ構造を使用していると思います。なぜなら、あなたは果物の名前に価格を関連付けるように思われるからです。 map<string,double>は、この作業に適しています:

#include <iostream> 
#include <map> 

int main(){ 
    std::string food; 
    std::map<std::string,double> priceForFood; 
    std::cout << "enter food and price or quit to finish:" << std::endl; 
    while(std::cin >> food && food != "quit") { 
     double price; 
     if (std::cin >> price) { 
      priceForFood[food]=price; 
     } 
    } 
    for (auto pair : priceForFood) { 
     std::cout << pair.first << " cost " << pair.second << std::endl; 
    } 
    return 0; 
} 

入力:

enter food and price or quit to finish: 
apples 100 
oranges 200 
quit 

出力:

apples cost 100 
oranges cost 200 
Program ended with exit code: 0