变量初始化错误c ++

时间:2017-11-13 21:08:05

标签: c++ arrays xcode initialization

使用数组处理一些代码,但是我不断收到错误"可能无法初始化变量大小的对象"对于数组中的变量,即使我在之前的行中将它们初始化为0。这是我的代码中的一段错误。

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

感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

您的代码

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

定义了一个可变长度数组items,它在C ++标准中不受支持,但仅限于特定的扩展。为了解决这个问题,您必须将xy声明为const(显然值为&gt; 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
相关问题