2015-11-20 145 views
-2

我有一个结构中有两个数组。我试图打印出每个数组的内容,但是当我完成所有工作时,无论我打印哪个元素,都无法获得字符串和零值。这些数组结构为什么不打印任何东西?

#include <iostream> 

using namespace std; 

struct menuItem 
{ 
    string breakfastItem[7]; 
    float itemPrice[7]; 
}dish; 

void setMenu() 
{ 
    dish.breakfastItem[0]= "Plain Eggs"; 
    dish.itemPrice[0]= 1.45; 
    dish.breakfastItem[1]= "Bacon and Eggs"; 
    dish.itemPrice[1]=2.45; 
    dish.breakfastItem[2]="Muffin"; 
    dish.itemPrice[2]=0.99; 
    dish.breakfastItem[3]="French Toast"; 
    dish.itemPrice[3]=1.99; 
    dish.breakfastItem[4]="Fruit Basket"; 
    dish.itemPrice [4]=2.46; 
    dish.breakfastItem[5]="Cereal"; 
    dish.itemPrice[5]=0.69; 
    dish.breakfastItem[6]= "Coffee"; 
    dish.itemPrice[6]=.50; 
    dish.breakfastItem[7]="Tea"; 
    dish.itemPrice[7]=0.75; 
} 

int main() 
{ 
    cout << dish.breakfastItem[0]; 
    cout << dish.itemPrice[0]; 
} 
+0

您应该刷新(假设您正在调试并在main的最后一个右大括号处有一个断点):'cout << dish.breakfastItem [ 0] << endl;' –

+4

你曾经调用过'setMenu()'函数吗? –

回答

2

首先,为了使setMenu()中的代码能够运行,您需要调用该函数。

int main() 
{ 
    setMenu(); 
    cout << dish.breakfastItem[0]; 
    cout << dish.itemPrice[0]; 
} 

其次

dish.breakfastItem[7]="Tea"; 
dish.itemPrice[7]=0.75; 

是因为你在过去书写的数组,然后不确定的行为。大小为7的数组的索引范围为[0,6]

+0

struct'menuItem'没有名为'setMenu'的成员是我在使用第一个代码时得到的错误。而对于未定义的行为,我有8个菜单项......这不是因为数组从0开始到7,我有8个序号? – Scotchdew

+0

@Scotchdew我修复了代码。用你的缩进我想'setMenu()'是'menuItem'的一部分。你没有8个项目。在'menuItem'中有'string breakfastItem [7];'它创建了一个包含7个项目的数组。如果你想要8,那么你需要'string breakfastItem [8];' – NathanOliver

+0

哦!有用!!非常感谢!我明白你的意思!虽然我正确地编写了代码,但数组中的序数数字却是崩溃的。再次感谢!你是男人! – Scotchdew

相关问题