The following program Assignment#2 was assigned to us a few weeks ago. I understood that assignment. Our professor told us soon we would be editting it to run more efficient. We have now been introduced to struct nodes. Needless to say, I am very confused. Our new assignment is due soon. Any help is appreciated.

Attachments
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

//Put in after std;
//Structure for Machine
struct Machine
{
    string drink_name;
    double drink_cost;
    int no_drinks;
}; //Semi colon of the GODZ!!

//Declare const variables
const int MAX = 5;

//Menu function
char menu();
//Intro function
void intro();
//Initialize function
void initialize(Machine m[MAX]);
//Display Machine function
void purchase(Machine m[MAX], double & sum);
//IF CALL BY VALUE
//double purchase(Machine m[MAX], double sum);
int main()
{
    //Declare local variables
    char opt;
    double amount;
    double sum = 0.0; //To store the amount of money earned

    //Declare machine type struct
    Machine m[MAX];

    //Set the values for the machine
    initialize(m);

    //Call intro
    intro();

    //FORMATTING THE OUTPUT
    cout << fixed << showpoint << setprecision(2);

    opt = 0;
    while(opt != '2')
    {
        opt = menu();
        switch(opt)
        {
            case '1':
                {
                purchase(m, sum);
                //IF CALL BY VALUE
                //sum = purchase(m, sum);
                } //End of case 1
            break;
            case '2':
                {
                cout << endl << "TODAY'S EARNINGS: " << sum << endl;
                cout << "Exiting" << endl;
                } //End of case 4
            break;
            default:
                {
                cout << "NOT AN OPTION" << endl;
                } //End of default case
        } //End of Switch
    } //End of while

    system("pause");
    return 0;
}//End of main()

/******************************************************************************/
char menu()
{
    //Declare input variable
    char choice;

    cout << "DRINK MACHINE MENU" << endl;
    cout << "(1) Pick a drink" << endl;
    cout << "(2) Quit" << endl;
    cin >> choice;
    cout << endl << endl;

    return choice;
}// End of menu()

/******************************************************************************/
void intro()
{
    cout << "Welcome to Roy's Drink Machine Program " << endl;
    cout << "Follow the menu and enjoy. " << endl;
    cout << endl << endl;
    system("pause");
    cout << endl << endl;
    //system("cls");
}

/******************************************************************************/
//Initialize function
void initialize(Machine m[MAX])
{
    m[0].drink_name = "Cola";
    m[0].drink_cost = .75;
    m[0].no_drinks = 20;
    m[1].drink_name = "Root Beer";
    m[1].drink_cost = .75;
    m[1].no_drinks = 20;
    m[2].drink_name = "Lemon-Lime";
    m[2].drink_cost = .75;
    m[2].no_drinks = 20;
    m[3].drink_name = "Grape Soda";
    m[3].drink_cost = .80;
    m[3].no_drinks = 20;
    m[4].drink_name = "Cream Soda";
    m[4].drink_cost = .80;
    m[4].no_drinks = 20;
} //End of initialize

/******************************************************************************/
//Display Machine function
void purchase(Machine m[MAX], double & sum)
//double purchase(Machine m[MAX], double sum)
{
    int choice;
    double amount;

    cout << "*********************************************************" << 
endl;
    cout << "*              SODAS LISTED 0 THROUGH 4                 *" << 
endl;
    cout << "* The types of drinks in the Machine are listed below!  *" << 
endl;
    cout << "*   Please enter the number for your chosen beverage!   *" << 
endl;
    cout << "*********************************************************" << 
endl;
    cout << endl;
    int j = 0;
    for(int i = 0; i < MAX; i++)
    {
        cout << "(" << j << ")   " << m[i].drink_name << endl;
        j++;
        //Checking to see if initialized correctly
        //cout << m[i].drink_cost << endl;
        //cout << m[i].no_drinks << endl;
    }
    cin >> choice;
    while((choice < 0)||(choice > 4))
    {
        cout << "NOT AN OPTION!!!" << endl;
        cout << "Please make another selection" << endl;
        cin >> choice;
    } //End of while
    while(m[choice].no_drinks < 1)
    {
        cout << "Sorry no more soda" << endl;
        cout << "Please pick a different drink" << endl;
        cin >> choice;
    } //End of While

    cout << endl << endl;
    cout << "The price of " << m[choice].drink_name << " is "
         << m[choice].drink_cost << " cents" << endl;

    cout << endl << endl;
    //Get the users money
    cout << "Please enter in the amount of cash" << endl;
    cin >> amount;

    //Make sure the user puts in between 0cents and a dollar
    while((amount < 0) || (amount > 1))
    {
            cout << "Please enter in the correct amount of cash" << endl;
            cin >> amount;
    } //End of while

    //Make sure the user puts in enough change
    while(amount < m[choice].drink_cost)
    {
            cout << "Please enter in the correct amount of cash" << endl;
            cin >> amount;
    } //End of while

    //If the amount is greater then cost return the users change
    if(amount > m[choice].drink_cost)
    {
        amount = amount-m[choice].drink_cost;
        cout << "Your change is " << amount << endl;
    } //End of if
    else
    {
        cout << "You have no change" << endl;
    } //End of else

    //Calculate the amount earned
    sum = sum + m[choice].drink_cost;

    //Decrement the no. the of sodas
    m[choice].no_drinks--;

    system("pause");
    cout << endl << endl;
    //system("cls");

    //IF CALL BY VALUE
    //return sum;
} //End of display

linked lists can be pretty confusion topic. you might want to study about them in more depth. Read one or more of the many tutorials you will find. Your text book should also have a chapter or two about them.

we were introduced to classes as well. should I use a class node instead of a struct node? should the functions to decrement the sodas be part of the data in the node or should it be separate? do I need two pointers or one to traverse the nodes and find the correct info to be used during use? thank you for your prompt response.

supes32

we were introduced to classes as well. should I use a class node instead of a struct node?

"struct" and "class" in C++ are actually the same thing with one very subtle difference - "struct" defaults to all members public, "class" defaults to all members private (use the public/private/protected keywords if the visibility of a member needs to be different). Which one you use is up to you, although, typicallylly 'struct' is used for simple data structures containing no functions, overloaded operators, etc.

For a linked list, you are undoubtedly going to be including functions, so 'class' would be the more idiomatic choice - It is considered good style to make your data members private and provide public functions as an interface to access the data.

should the functions to decrement the sodas be part of the data in the node or should it be separate?

As a rule of thumb, put the function to manipulate the data inside the structure in which that data is kept (keeping the data private means that non-member functions can't access it anyway).

do I need two pointers or one to traverse the nodes and find the correct info to be used during use?

Judging by your assignment, you are only going to traverse the list in one direction, so you only need a single pointer to the next element.

I had a little trouble with linked lists when I was learning.. so I whipped up a little something to get you started:

#include<iostream>
#include<fstream>
#include<sstream>
#include<cstdlib>
#include<iomanip>
#include<cctype>
#include<string>
#include<windows.h>
using namespace std;


struct Node
{
   string name;
   double cost;
   int    quantity;   
   Node   *next;
};

class Soda
{    
   public:
          
      Soda();
      ~Soda();
      void reset();
      void display();            
      void get_soda_config();
      void set_soda_config();
      void load_machine();
      void dispense();
      void prompt();
      void calc_change();
      void gotoxy(int x, int y);
      void clrscr();
      void pop_nodes();
      bool again();
          
   private:           
      
      Node *head_ptr;
      HANDLE hOut;
      ifstream infile;      
      int selection,
          soda_quantities[5],          
          x_coords[5][15],
          y_coords[5][15]; 
      double amount,
             change,
             soda_prices[5];              
};

enum Flavors{ Cola, CreamSoda, Grape, LemonLime, RootBeer };       


int main()
{
    Soda Machine;    
 
    Machine.get_soda_config();
    Machine.set_soda_config();
    Machine.display();
    
    do{
                                                     
         Machine.prompt();
         Machine.dispense();          
         Machine.display();
         Machine.reset();
         
      }while(Machine.again()); 
     
   return EXIT_SUCCESS;
}



////////////////////////////////////////////////////////////////
////////////  Function Definitions   //////////////////////////
//////////////////////////////////////////////////////////////


Soda::Soda()
{            
   reset();   
   hOut = GetStdHandle ( STD_OUTPUT_HANDLE );
   
     for(int i=0; i<5; i++)
   {    
       soda_quantities[i] = 0;
       soda_prices[i] = 0.0;
   }
   
   for(int i=0, k=17; i<5; i++, k+=8)
      for(int j=0; j<15; j++)
      
           x_coords[i][j] = k;
           
   for(int i=0; i<5; i++)
      for(int j=0, k=31; j<15; j++, k--)
      
           y_coords[i][j] = k;
}

Soda::~Soda()
{             
   while(head_ptr)
   
      pop_nodes();
}      

void Soda::display()
{     
     WORD wOldColorAttrs;     
     CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
     
     clrscr();
     
     GetConsoleScreenBufferInfo(hOut, &csbiInfo);
     wOldColorAttrs = csbiInfo.wAttributes;     
     SetConsoleTextAttribute(hOut, BACKGROUND_RED | BACKGROUND_INTENSITY);
     SetConsoleTextAttribute(hOut, FOREGROUND_GREEN | FOREGROUND_BLUE);
     
     cout << endl << endl << endl;
     cout << "\t __________________________________________     \n";
     cout << "\t|\\                                         \\  \n";
     cout << "\t| \\                                         \\ \n";
     cout << "\t|  \\ ________________________________________\\\n";
     cout << "\t|\\  |                                         |\n";
     cout << "\t| \\ |            Machine o' Drink             |\n";
     cout << "\t|  \\|_________________________________________|\n";
     cout << "\t|   |                                         |\n";
     cout << "\t|   |                                         |\n";
     cout << "\t|   |         Cream           Lemon    Root   |\n";
     cout << "\t|   |  Cola     Soda   Grape    Lime    Beer  |\n";
     cout << "\t|   |                                         |\n";
     cout << "\t|   |   " << soda_prices[Cola]  
          << setw(8) << soda_prices[CreamSoda]
          << setw(8) << soda_prices[Grape]
          << setw(8) << soda_prices[LemonLime]
          << setw(8) << soda_prices[RootBeer]; gotoxy(54,15); cout  << "|\n";
     cout << "\t|   |  _____   _____   _____   _____   _____  |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";  
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |     | |     | |     | |     | |     | |\n";
     cout << "\t|   | |_____| |_____| |_____| |_____| |_____| |\n";
     cout << "\t|   |                                         |\n";
     cout << "\t|   |             _______                     |\n";
     cout << "\t\\   |            |       |                    |\n";
     cout << "\t \\  |            |_______|                    |\n";
     cout << "\t  \\ |                                         |\n";
     cout << "\t   \\|_________________________________________|\n";
     
     SetConsoleTextAttribute (hOut, wOldColorAttrs);     
     load_machine();        
}

void Soda::prompt()
{
     int choice     = 0;
     double tempAmt = 0.0;
     string tempString;     
     
     gotoxy(6, 40);     
     cout << "\n\n\tEnter 'Q' to Quit" << endl;
     
     while(amount < .75)  
     {    
          if(amount)
          {
             cout << "\n\n\tCurrent Amount Entered:  $" << amount; 
             cout << "\n\t----------------------"     << endl;
          }        
          cout << "\n\tEnter amount into machine:  $ ";
          cin >> tempString;
          if(tempString == "Q" || tempString == "q")
             exit(EXIT_SUCCESS); 
          istringstream atol(tempString);
          atol >> tempAmt;
          amount += tempAmt;                               
     };
     
     clrscr();
     display();
     gotoxy(6, 40); 
     
     do{               
          cout << "\n\n\t  Selection";
          cout << "\n\t-----------------\n";
          cout << "\n\t1. Cola";
          cout << "\n\t2. Cream Soda";
          cout << "\n\t3. Grape";
          cout << "\n\t4. Lemon Lime";
          cout << "\n\t5. Root Beer";
          cout << "\n\n\t Enter Choice: ";
          cin >> selection;
     }while(selection < 1 || selection > 5);
     
     if(selection == CreamSoda || selection == LemonLime)
        if(amount < .80)
        {
           cout << "\n\t\aNot enough dinero!  Please enter mo' money";
           Sleep(1500);
           prompt();
        }  
        
     else if(toupper(selection) == 'Q')
     
          exit(EXIT_SUCCESS);
 
}

void Soda::gotoxy(int x, int y)
{
  COORD coord;
  coord.X = x;
  coord.Y = y;
  SetConsoleCursorPosition(hOut, coord);
} 

void Soda::get_soda_config()
{
     string data;
     Node *tempNode = NULL, 
          *prevNode = NULL;
     
     infile.clear();
     
     //Source path can be modified to meet the needs of the user
     infile.open("C:\\soda.txt");
     
     if(infile.fail())
     {
        cout << "\n\n\t\aError!  Source File Could NOT Be Found...";
        cout << "\n\tProgram Will Now Terminate.";            
        MessageBox(NULL, "Error! Source File NOT Found.", "Soda Machine", MB_ICONERROR);
        exit(EXIT_FAILURE);
     }     
     
     try{tempNode = new Node;}
     catch(bad_alloc)
     {
        cout <<"\n\n\t\aError!  Not Enough Available Memory!";
        cout <<"\n\tPlease shut down any non-vital applications and try again";
        MessageBox(NULL, "Error! Out of Available RAM.", "Soda Machine", MB_ICONERROR);
        exit(EXIT_FAILURE);
     }     
     
     if(!head_ptr)
     
        head_ptr = tempNode; 
     
     while(infile >> tempNode->name)
     {
        infile >> tempNode->cost;
        infile >> tempNode->quantity;
        prevNode = tempNode;
        tempNode = new Node;
        prevNode->next = tempNode;
     }     
       
     prevNode->next = NULL;
     delete tempNode;
     infile.close(); 
}  

void Soda::set_soda_config()
{
     int  index = 0;
     Node *temp = NULL;
     
     if(head_ptr)
     
        temp = head_ptr;
        
     else
     
        return;
     
     while(temp)
     {
        if(temp->name == "Cola")
        {
           soda_prices[Cola] = temp->cost;
           soda_quantities[Cola] = temp->quantity;
        }           
        else if(temp->name == "CreamSoda")
        {
           soda_prices[CreamSoda] = temp->cost;
           soda_quantities[CreamSoda] = temp->quantity;
        }        
        else if(temp->name == "Grape")
        {
           soda_prices[Grape] = temp->cost;  
           soda_quantities[Grape] = temp->quantity;
        }
        else if(temp->name == "LemonLime")
        {
           soda_prices[LemonLime] = temp->cost;
           soda_quantities[LemonLime]= temp->quantity;
        }
        else if(temp->name == "RootBeer")
        {
           soda_prices[RootBeer] = temp->cost;  
           soda_quantities[RootBeer] = temp->quantity;
        }
     
        temp = temp->next;
     }
}

void Soda::load_machine()
{
     for(int i=0; i<5; i++)
        for(int j=0; j<soda_quantities[i]; j++)
        {
           gotoxy(x_coords[i][j], y_coords[i][j]);
           cout << "O";
        }
}   

void Soda::dispense()
{
     if(!soda_quantities[selection-1])
     {
        cout << "\n\n\t\a     ** SOLD OUT **";
        cout << "\n\n\tPlease make another selection ";
        Sleep(1500);
        display();
        prompt();        
     }
     else
             
        display();
                  
     gotoxy(6, 42);
     --soda_quantities[selection-1]; 
     change = amount - soda_prices[selection-1];
     cout << "Ye' change is $" << change;
     Sleep(1500);
}   

void Soda::clrscr()
{
    COORD                       coordScreen = { 0, 0 };
    DWORD                       cCharsWritten;
    CONSOLE_SCREEN_BUFFER_INFO  csbi;
    DWORD                       dwConSize;
    HANDLE                      hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    GetConsoleScreenBufferInfo(hConsole, &csbi);
    dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
    FillConsoleOutputCharacter(hConsole, TEXT(' '), 
                               dwConSize, coordScreen, &cCharsWritten);
    GetConsoleScreenBufferInfo(hConsole, &csbi);
    FillConsoleOutputAttribute(hConsole, csbi.wAttributes, 
                               dwConSize, coordScreen, &cCharsWritten);
    SetConsoleCursorPosition(hConsole, coordScreen);
}  

void Soda::reset()
{
   head_ptr = NULL; 
   infile.clear();  
   selection = 0;
   amount =  0.0;
   change =  0.0;
} 

void Soda::pop_nodes()
{
     Node *temp = NULL;
     
     temp = head_ptr;
     head_ptr = head_ptr->next;
     delete temp;
}
     
bool Soda::again()
{
     char answer;
     
     gotoxy(6, 45); 
     cout << "\n\n\tWould ye' like another refreshing soda? (Y/N) ";
     cin >> answer;
     display();
      
     if(toupper(answer) == 'Y')
      
        return true;
        
     else
     
        return false;   
}

Unless you modify the path in get_soda_config(), you will need to have a .txt file in your c:\ folder with the information arranged like this:

RootBeer .75 0
Grape .75 15
Cola .75 2
LemonLime .80 1
CreamSoda .80 10

The lines can be in any order as long as they maintain the product price quantity format.

Let me know if you have any questions.

>so I whipped up a little something to get you started:

You mean you've whipped up his entire assignment... Note the difference. :rolleyes:

>Let me know if you have any questions.

Erm how much is he paying you? :rolleyes:

Good stuff though, I like the little ascii art. Do you really have that much free time on your hands?

This article has been dead for over six months. Start a new discussion instead.