2016-03-20 3 views
0

Я пытаюсь перебрать структуры, а не поля для создания торгового автомата, такого как программа. Я не понимаю, почему это не работает:Мне нужно прокручивать структуру

//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 

Пожалуйста, обратите внимание, что мы не покрыли классы и объекты в моем классе еще, так что я не могу их использовать еще в течение некоторого простого ввода/вывода материала за исключением и класс строки.

EDIT: 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 
} 

EDIT: теперь он компилирует, но он выходит из строя отображения второго элемента в торговом автомате

+0

вы можете дать свой полный код .. –

+1

Вы знаете, что 'закуска specificSnack [CHIPS]' создает массив 'CHIPS' числа' snack' структур? И учитывая, что 'CHIPS' равен нулю, это не будет работать очень хорошо. Возможно, вы хотите ['std :: map'] (http://en.cppreference.com/w/cpp/container/map) или, возможно, [' std :: vector'] (http: // ru. cppreference.com/w/cpp/container/vector)? То, что вам определенно нужно, - это [The Definitive C++ Book Guide and List] (http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). –

+1

ваш код не имеет смысла И не будет компилироваться .. что вы ожидаете 'snack specificSnack [CHIPS] = {« Чистые картофельные чипы », 15, 1.00};' делать? здесь вы не строите закуски, вы определяете массив закусок, а затем пытаетесь инициализировать его аргументами, которые вы обычно передадите конструктору одной закуски ... Затем 'for (int i = CHIPS; i

ответ

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}; 
    ... 
} 
+0

Нужно ли устанавливать каждое значение в списке? –

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

спасибо, теперь он компилируется. –

+1

Да, я знаю. Я не изучил, что еще делает ваш код, но - поскольку вы неправильно поняли что-то такое фундаментальное - я бы не стал парировать, что остальная часть вашего кода работает по назначению. Вам нужно будет отлаживать самостоятельно - этот формат не подходит для повторения «пожалуйста, заработайте мой код, и я отредактирую вопрос каждый раз, когда кто-то помогает с одной проблемой, пока я не получу свой рабочий код». – Peter

+0

ОК, спасибо. знаете ли вы, что на каком-либо сайте этот формат будет приемлемым? И да, я знаю, что это фундаментально, но я только кодировал несколько месяцев, и это мой первый опыт работы со структурами и счетчиками. –

Смежные вопросы