我需要循环一个结构

时间:2016-03-20 09:11:06

标签: c++ c++11 data-structures struct structure

我正在尝试遍历结构,而不是创建像程序一样的自动售货机的字段。我不明白为什么这不起作用:

//create a structure to hold data on the items in the vending machine
struct snack{

    string description; //this will hold data on what the item is
    int quantity;       //this will hold data on how many of the item are left in the vending machine
    double cost;        //this will hold the cost of this item

};

//...

//create the specific snack structures of type snack and initialize them
snack specificSnack[CHIPS]={"Plain Potato Chips", 15, 1.00};
snack specificSnack[SNICKERS]={"Snickers", 10, 0.75};
snack specificSnack[PEANUTS]={"Peanuts", 15, 1.00};
snack specificSnack[JOLLYRANCHER]={"Jolly Rancher", 10, 0.75};
snack specificSnack[APPLE]={"Apple", 5, 0.50};

//...

//print a header
cout<<"\n#  |cost  |quantity |item"<<endl:

//display all the items in the menu
for(int i=CHIPS; i<EXIT; i++)
    displayMenu(specificSnack[i], i); //call the display for a specific item

请注意我们没有涵盖课程中的类和对象,所以除了一些简单的i / o东西和字符串类之外我还不能使用它们。

编辑:CHIPS,SNICKERS等..是枚举变量。

//create an enumerated variable of type treat to make the code more readable and select choices
enum treat{CHIPS, SNICKERS, PEANUTS, JOLLYRANCHER, APPLE, EXIT};

当然,这是完整的代码[更新]:

//This is a simple vending machine emulator
//Developed by [NAME WITHHELD]
//created on: 3/19/2016 8:30 AM
//last updated on: N/A

//library includes
#include <iostream>     //in/out functionality
#include <iomanip>      //used for in/out manipulators such as endl
#include <string>       //used to process string objects
#include <cstring>      //used to process c style strings
using namespace std;    //this tells the compiler that the libraries are located in the standard location

//create a structure to hold data on the items in the vending machine
struct snack{

    string description; //this will hold data on what the item is
    int quantity;       //this will hold data on how many of the item are left in the vending machine
    double cost;        //this will hold the cost of this item

};

//create an enumerated variable of type treat to make the code more readable and select choices
enum treat{CHIPS, SNICKERS, PEANUTS, JOLLYRANCHER, APPLE, EXIT};


void vend(int choice, snack & specificSnack);
void finalOutputDisplay(long double totalCost);
treat getChoice();
void displayMenu(snack selection, int i);

//program starts here
int main()
{
    //pre-configure cout for numerical output
    cout<<fixed;


    snack specificSnack[APPLE];

    //create the specific snack structures of type snack and initialize them
    specificSnack[CHIPS]={"Plain Potato Chips", 15, 1.00};
    specificSnack[SNICKERS]={"Snickers", 10, 0.75};
    specificSnack[PEANUTS]={"Peanuts", 15, 1.00};
    specificSnack[JOLLYRANCHER]={"Jolly Rancher", 10, 0.75};
    specificSnack[APPLE]={"Apple", 5, 0.50};

    //create a variable to hold the total amount the user is going to spend in this session
    long double totalCost=0;

    //create and enumerated variable called choice, of type treat
    treat choice=CHIPS;

    //begin looping until we see the EXIT sentinel
    while(choice!=EXIT)
    {
        //print a header
        cout<<"\n#  |cost  |quantity |item"<<endl;

        //display all the items in the menu
        for(int i=CHIPS; i<EXIT; i++)
            displayMenu(specificSnack[i], i); //call the display for a specific item

        //get the user's selection
        choice=getChoice();

        //skip the vending code if we are exiting
        if(choice!=EXIT)
        {
            //make sure the item isn't sold out
            if(specificSnack[choice].quantity!=0)
                totalCost=specificSnack[choice].cost;//add the cost of the item chosen to the running total

            //run the vending code to decrement the quantity of the item and display
            //a message confirming the selection
            vend(choice, specificSnack[choice]);

        }
    }//return to the start of the loop and run a check to see if we break on EXIT

    //display the total cost of items bought in this session and
    finalOutputDisplay(totalCost);

    return 0;   //return to the OS
}

void displayMenu(snack selection, int i)
{
    //print out one line/option of the menu

    //print the cost of the item
    cout<<i<<". |"<<setprecision(2)<<setw(6)<<selection.cost<<"|";

    //check if we are sold out
    if(selection.quantity!=0)
        cout<<setprecision(0)<<setw(9)<<selection.quantity<<"|";    //print the amount left
    else
        cout<<"Sold Out |";  //tell the user we're sold out

    //give the item
    cout<<selection.description<<endl;

    return; //exit function
}

treat getChoice()//get the user's choice, decide if it's valid and what it is, and return it in the proper format
{
    //create variables
    string usrInput;
    treat choice;
    int i;
    bool continueLoop;

    //begin a loop to catch invalid input
    do
    {
        cout<<"\nPlease select an item: ";  //prompt the user
        i=0;    //reset the loop control variable for the uppercase letter to lowercase letter conversion loop
        continueLoop=0; //reset the flag to break out of the do-while loop

        //get & store user input
        getline(cin, usrInput);

        //loop through the string
        while(usrInput[i]!='\0')
        {
            //check if the letter is a capital
            if(isupper(usrInput[i]))
                tolower(usrInput[i]);//convert the character to a lowercase letter
            i++;//increment out loop control variable and proceed to the next character in the string
        }

        //check if the user entered a valid choice and set choice appropriately
        if(usrInput=="1" || usrInput=="one" || usrInput=="chips" || usrInput=="plain potato chips")
            choice=CHIPS;
        else if(usrInput=="2" || usrInput=="two" || usrInput=="snickers")
            choice=SNICKERS;
        else if(usrInput=="3" || usrInput=="three" || usrInput=="peanuts")
            choice=PEANUTS;
        else if(usrInput=="4" || usrInput=="four" || usrInput=="jolly rancher")
            choice=JOLLYRANCHER;
        else if(usrInput=="5" || usrInput=="five" || usrInput=="apple")
            choice=APPLE;
        else if(usrInput=="6" || usrInput=="six" || usrInput=="exit")
            choice=EXIT;
        //catch invalid input
        else
        {
            //throw an error message
            cout<<"\aERROR! Please enter a valid choice!"<<endl;

            //flip the flag to continue the loop again
            continueLoop=1;
        }

    }while(continueLoop);//check if the flag was flipped


    return choice;//return the user's choice in the proper format.
}

void vend(int choice, snack & specificSnack)//tell the user what we are vending, or display sold out
{
    //give the items name
    cout<<"\nITEM: "<<specificSnack.description<<endl;
    //give the items price
    cout<<"COST: $"<<specificSnack.cost<<endl;
    //check if we are sold out and if we aren't run the following code
    if(specificSnack.quantity>0)
    {
        //tell the user we are vending
        cout<<"Vending..."<<endl;

        //remove one item from the machine
        specificSnack.quantity--;
    }
    //if we are sold out do this:
    else
    {
        //display a sold out message
        cout<<"\a\n!SOLD OUT!: "<<specificSnack.description<<endl;
    }

    return; //exit function
}

void finalOutputDisplay(long double totalCost)  //display a final message to the user including their total
{
    //be polite & friendly to our customer
    cout<<"\nThank you for using this vending machine!  Have a nice day!"<<endl;
    //display the total spent by the user in this session
    cout<<"\nYour total is: "<<totalCost<<endl;
    //display a message saying the session is ending
    cout<<"\nNow exiting session..."<<endl;

    return; //exit function
}

编辑:它现在编译,但它崩溃显示自动售货机中的第二个项目

2 个答案:

答案 0 :(得分:1)

  

snack specificSnack[CHIPS]={"Plain Potato Chips", 15, 1.00};

想想这在C ++中意味着什么。

它将specificSnack定义为具有CHIPS类型snack元素的数组。它不会创建标识为snack的单个specificSnack[CHIPS]

这样做之后 - 假设它编译 - 下一个声明

  

snack specificSnack[SNICKERS]={"Snickers", 10, 0.75};

specificSnack定义为具有SNICKERS类型snack元素的数组。 C ++有一个“一个定义规则”,这意味着,在定义任何数组时,只允许一个定义。数组的两个定义 - 特别是具有不同的维度 - 打破了这一规则。

你能做的最多就是定义一次数组,然后初始化它。

例如;

enum treat{CHIPS=0, SNICKERS=1, PEANUTS=2, JOLLYRANCHER=3, APPLE=4, EXIT=5, number_of_treats = 5};    // assuming EXIT is not deemed to be a treat

 snack specificSnack[number_of_treats] = {
            {"Plain Potato Chips", 15, 1.00},
            {"Snickers", 10, 0.75}, 
            {"Peanuts", 15, 1.00},
            {"Jolly Rancher", 10, 0.75},
            {"Apple", 5, 0.50}};

答案 1 :(得分:0)

我认为你的意思是:

...
enum treat{CHIPS=0, SNICKERS=1, PEANUTS=2, JOLLYRANCHER=3, APPLE=4, EXIT=5};
...
int main() {
    ...
    snack specificSnack[6];
    specificSnack[CHIPS]       ={"Plain Potato Chips", 15, 1.00};
    specificSnack[SNICKERS]    ={"Snickers", 10, 0.75};
    specificSnack[PEANUTS]     ={"Peanuts", 15, 1.00};
    specificSnack[JOLLYRANCHER]={"Jolly Rancher", 10, 0.75};
    specificSnack[APPLE]       ={"Apple", 5, 0.50};
    ...
}
相关问题