2017-11-13 2 views
-4

배열을 사용하는 일부 코드에서 작업하지만 배열의 변수에 대해 "변수 크기의 개체가 초기화되지 않을 수 있습니다."오류가 계속 발생합니다. 이전에 줄을 0으로 초기화하더라도. 다음은 오류가 발생한 코드입니다.변수 초기화 오류 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