Thread: Calling a function with structure elements.

  1. #1
    Registered User SiriusWhite's Avatar
    Join Date
    Mar 2014
    Location
    Jamaica
    Posts
    9

    Calling a function with structure elements.

    Code:
    const MenuData breakfast[NUMOFBREAKFASTITEMS] = {
    
      {"Egg Breakfast", "Two eggs with a side of bacon and two slices of toast.", "", "2 Eggs, 2 Toats, 2 Bacons", "", 250.00},
    
    
      {"Pancake Breakfast", "Three Buttermilk pancakes served with butter and syrup.", "", "Three Pancakes, Butter, Syrup", "", 200.00},
    
    
      {"Meat Variety", "Three eggs and a full order of bacon and", "smoked sausages served with porridge, three fried dumplings and jam.", "1 Bowl Poridge,", "3 Fried Dumplings, Jam", 350.00}
    
    
    };
    
    
    const MenuData lunch[NUMBEROFLUNCHITEMS]= {
        
        {"Cheese Burger", " Thick-sliced bacon and two slices of tastee", "cheese served with seared buns and fries.", "Cheese Burger, Fries", "", 450.00,},
        
        {"Hotdog N' Fries", "Smoked sausages served between Hotdog Rolls with seasoned Fries.", "", "Smoked Sausage Hotdog, Seasoned Fries", "", 345.60,},
        
        {"Chicken Feet Soup", "Chicken feet soup served with boiled dumplings", "yellow yam, sweet potato and 5 slices of garlic bread.", "Chicken soup- Boiled Dumplings, Yellow", "Yam, Sweet Potato, 5 Garlic Bread", 445.60}
        
    };
    
    
    const MenuData dinner [NUMBEROFDINNERITEMS]= {
        {"Sunday Dinner", "Fried Chicken served with rice and peas and macaroni salad", "", "Fried Chicken, Rice and Peas, Macaroni Salad", "", 600.00,},
        
        {"Pastas N' Such", "Macaroni casserole topped with an assortment of cheese","served with mashed potatoes and baked chicken", "Macaroni Casserole, Four Cheese Topping", "Mashed Potatoes, Baked Chicken", 450.00,},
        
        {"Real Jamaican Dinner", "Ackee and saltfish served with boiled dumplings", "yam and irish potatoes", "Ackee and Saltfish, Boiled dumplings, Yam", "", 395.00,}
    };
    
    
    const MenuData dessert [NUMBEROFDESSERTITEMS]= {
        {"Rock Cakes","", "", "Rock Cakes", "", 70.00,},
        
        {"Gizzarda", "", "", "Gizzarda", "", 95.50,},
        
        {"Fruit Cake", "", "", "Fruit Cake", "", 200.00,},
        
        {"Apple Pie Slice", "", "", "Apple Pie Slice", "", 300.00,},
        
        {"Cheese Cake Slice", "","", "Cheese Cake Slice", "", 300.00,},
        
        {"Fudge Cupcake", "","", "Fudge Cupcake", "", 100.00,}
        
    };
    
    
    const MenuData beverage [NUMBEROFBEVERAGEITEMS]= {
        {"Hot Chocolate", "", "", "Hot Chocolate", "", 60.00,},
        
        {"Coffee", "", "", "Coffee", "", 50.00,},
        
        {"Soft Drink", "", "", "Soft Drink", "", 90.00,},
        
        {"Beer", "", "", "Beer", "", 150.00,},
        
        {"Wine", "", "", "Wine", "", 250.00,},
        
        {"Water", "", "", "Water", "", 75.00,}
    
        
    };
    
    void printReceipt (const MenuData menu[], int qty, info)
    {
        info in1;
        int i;
        enum options choices;
        float subtot, subtotal;
        float total, ctender, Tax;
        float outstanding, balance;
        
        for(i=0; i<qty; i++)
        {
             subtot= subtot + (menu[i].price*qty);
        }
         
        total= subtot* TAX;
        Tax=total;
        printf ("The Total is: %.2f\n");
        printf ("Enter the cash tendered by customer: ");
        scanf ("%f", &ctender);
         
        if (ctender< total)
        {
             outstanding= total- ctender;
             printf ("The customer has %.2f outstanding", outstanding);
             printf ("Enter the outstanding balance: ");
             scanf ("%f", &balance);
        }
         
        change= total- ctender;
        printf ("The Chnage is: %.2f", change);
         
         
        system ("cls");
        printf ("To Print Receipt, "); system ("pause");
        
        printf ("                      8         \n");
        printf ("                      88        \n");
        printf ("                      88ooo.    \n");
        printf (" oo. .o. .oo   oo d8b d8'  `8b  \n");
        printf (" 88P'Y88'Y88   88'    88    88  \n");
        printf ("o88o     o88o d88b    `YbodP'  \n");
        printf ( "\n");
        printf ("        ** RECIEPT**           \n");
        printf ("\n");
        printf ("\n");
        printf ("5 Kingston Road, Lot 5\n");
        printf ("Cashier Name: %s", in1.Cname); 
        printf ("\n");
        printf ("\n");
        printf ("Item Bought      QTY        Price\n");
        
        for(i=0; i<qty; i++)
        {
            printf ("%s \t%d \t$ %.2f\n", menu[i].name, qty, menu[i].price);
            printf ("Subtotal                $ %.2f\n", subtotal);
            printf ("TAX                     $ %.2f\n", Tax);
            printf ("Toatl Sale              $ %.2f\n", total);
            printf ("Cash Tendered           $ %.2f\n", ctender); 
            printf ("\n");
        }
    }
    What I'm trying to do is call the printReceipt function in the main, but I'm doing it wrong. Here is my attempt.

    Code:
    printReceipt (const MenuData menu[], qty, info)
    I've tried it many other ways but I keep getting an error. I tried researching it on the internet, but I don't get much info.

  2. #2
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    I the function header void printReceipt (const MenuData menu[], int qty, info) - what is 'info'? It's not a basic data type. So where is the formal parameter?
    Also, can you show the part of 'main' where you call the function.

  3. #3
    Registered User SiriusWhite's Avatar
    Join Date
    Mar 2014
    Location
    Jamaica
    Posts
    9
    Quote Originally Posted by nonoob View Post
    I the function header void printReceipt (const MenuData menu[], int qty, info) - what is 'info'? It's not a basic data type. So where is the formal parameter?
    Also, can you show the part of 'main' where you call the function.
    I made a lot of changes though, I made separate functions for calculations and took out the 'info' that was a structure.
    Code:
    int main (){
        interface ();
        info in1;
            MenuData menu;
        int psw, mmchoice, count=3;
        enum MenuTime Mchoice;
    
    
        for (int i=0; i<count; i++)
        {
            printf ("\n\t\tEnter Your Cashier Name: ");
            scanf ("%s", in1.Cname);
            printf ("\n");
            printf ("\n\t\tEnter the Password: ");
            scanf ("%d", &psw);
        
            system ("cls");
            system ("pause");
            
               if (psw==1234)
            {
                 interface ();
                 
                 FILE *cfPtr;
                if ((cfPtr= fopen ("Food.txt", "a"))==NULL)
                 {
                   printf ("File could not be opened\n");
                 }
                 
                 printf ("\n");
                printf ("Enter the Client's name\n:"); 
                scanf ("%s", in1.cFname);
                printf ("\n");
                
                printf ("Enter the Client's Table number\n:");
                scanf ("%d", &in1.customerNum);
                
                fprintf (cfPtr, "\n");
                fprintf (cfPtr, "Customer Name: %s\n", in1.cFname);
                fprintf (cfPtr, "Table Number: %d\n", in1.customerNum);
                
                
                while (1)
                 { 
                    fflush (stdin);
                    system ("cls");
                    interface ();
                    printf ("\n");
                    printf ("---------------#Welcome to Main Menu#----------------\n");
                    printf ("\n");
                    printf ("\tPress 1 for the Breakfast Menu\n");
                    printf ("\tPress 2 for the Lunch Menu\n");
                    printf ("\tPress 3 for the Dinner Menu\n");
                    printf ("\tPress 4 for the Desert Menu\n");
                    printf ("\tPress 5 for the Beverage Menu\n");
                    printf ("\tPress 6 to Exit\n");
                    scanf ("%d", &Mchoice);
         
                    switch (Mchoice) 
                    {    
                        case Breakfast:        
                            system ("cls");
                            printf ("\t.........Breakfast Menu............\n");
                            displayMenu(breakfast, NUMOFBREAKFASTITEMS);
                            orderFunction (breakfast, NUMOFBREAKFASTITEMS);
                            getch ();
                            break;
                   
                         case Lunch:
                             system ("cls");
                             printf ("\t.........Lunch Menu..........\n");
                            displayMenu(lunch, NUMBEROFLUNCHITEMS);
                            orderFunction (lunch, NUMBEROFLUNCHITEMS);
                            getch ();
                            break;
                
                        case Dinner:
                            system ("cls");
                            printf ("\t.........Dinner Menu.........\n");
                            displayMenu (dinner, NUMBEROFDINNERITEMS);
                            orderFunction (dinner, NUMBEROFDINNERITEMS);
                            getch ();
                            break;
                    
                        case Dessert:
                            system ("cls");
                            printf ("\t.........Desseert Menu.........\n");
                             displayMenu (dessert, NUMBEROFDESSERTITEMS);
                             orderFunction (dessert, NUMBEROFDESSERTITEMS);
                             getch ();
                            break;
                    
                        case Beverage:
                               system ("cls");
                               printf (".........Beverage Menu........\n");
                               displayMenu (beverage, NUMBEROFBEVERAGEITEMS);
                               orderFunction (beverage, NUMBEROFBEVERAGEITEMS);
                               getch ();
                               break;
                               
                           case DoCalculations:
                               EnterData ();
                            CalChange (ctender, total);       
                               break;
                               
                           case Receipt:
                               printReceipt (menu, NUMOFBREAKFASTITEMS, subtot, total);// this is where I called the function
                               break;
                               
                        case Exit:    
                            exit (1);
                            break;
        
                    
                           default:
                             printf ("This Option Doesn't Exist\n");
                              break;

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Code:
    void printReceipt (const MenuData menu[], int qty, info)
    How many parameters does printReceipt take? And how many are you passing it?
    Code:
    printReceipt (menu, NUMOFBREAKFASTITEMS, subtot, total);
    When declaring, defining and calling a function, the return types must match, as must the number of parameters, their types and the order you pass them in.

  5. #5
    Registered User SiriusWhite's Avatar
    Join Date
    Mar 2014
    Location
    Jamaica
    Posts
    9
    the number of parameters is 3, and everything matches and adds up. I think it may have something to do with the structure menu. I tied calling the objects in the structure separately but that does not work either
    Last edited by SiriusWhite; 03-07-2014 at 11:32 AM.

  6. #6
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by SiriusWhite View Post
    the number of parameters is 3, and everything matches and adds up. I think it may have something to do with the structure menu. I tied calling the objects in the structure separately but that does not work either
    Look at the two pieces of code in my post (which I took directly from your code that you posted). In the first one, you declare it to have 3 parameters. In the second one, you call it with 4 parameters. That is a problem. Furthermore, as Tim pointed out, we don't know what exactly info is (it appears to be a struct, but not sure), but subtot and total are almost certainly the wrong types (they're floats).

    I can't read your mind, or your computer. I can only comment on what you post on this forum. So if your code has changed, then post the updated code -- all of it -- so we can actually help you with your program, instead of working on some older version you aren't using anymore.

    All in all, your code is pretty decent. Still, I will take this time to comment on a few more things. The first ~5-7 are more important, the rest are fairly trivial, but worth fixing IMO:

    1. fflush (stdin); is undefined behavior. Read this link. It links you to this page with an alternative that is well-defined behavior and works on any system (the getchar loop).
    2. system("cls") and system("pause") are Windows specific. They wont work on other systems, so your code is technically broken on my system (I use Linux), making it harder for me to help you. Besides, most people find excessive pauses and clearing of the screen annoying.
    3. getch() is also non-standard and Windows-specific (there is a Linux getch(), but it does something different). Instead, just use the standard getchar() function.
    4. If you can't open a seemingly critical file like Food.txt, you should probably consider terminating the program. No point in trying to continue reading from cfPtr if it doesn't refer to a valid, opened file. Just return an error code from main.
    5. Don't use magic numbers (like 1234 for password -- and spell out password for the variable). Instead, #define it as a constant so you can change it easily.
    6. I don't know if you are yet, but compile at the maximum warning level. Fix all errors and warnings. Most warnings suggest problematic code.
    7. You should check the value of file and input functions like scanf. If somebody types in character data by mistake, you can get stuck in an infinite loop. scanf returns the number of things correctly scanned, i.e. the number of % things in your format string. See below for an example:
    8. Your code looks pretty well organized, formatted and indented (certainly in your first post), so good job on that. Two minor notes:
    9. Your second post is not as nice. Make sure you paste as plain text so our syntax highlighter can do it's job, and click the "preview" button to make sure it looks right, before you post. If not, fix any formatting indentation issues.
    10. Some of your lines with menu data are quite long. That makes it hard to read. Stick to ~80-120 chars per line, breaking at logical spots (e.g. between different struct elements).
    11. Most of your names are clear and descriptive, which is very good. A few notes though:
    12. Don't abbreviate too much. What is ctender? change_tendered? cash_tendered? chicken_tenders?
    13. Having a variable subtot and another, subtotal, is confusing. They both suggest the same exact thing, so I can't figure out what you're trying to do with each.
    14. Why are some of your variables capitalized (e.g. Tax, Mchoice)? Pick one naming convention and stick to it.
    15. You can use common abbreviations though and use some underscores to separate words. Plus, you can omit very small words. For example, your constants: NUM_LUNCH_ITEMS is much easier to read than NUMBEROFLUNCHITEMS, and just as descriptive.

    Example
    Code:
    void flush_input_buffer(void)
    {
        // here is the standard, portable code from the above link, to flush the input buffer
    }
    ...
    if (scanf("%d", &menu_choice) != 1) {
        // no integer data read
        // print error message for invalid input
    }
    // always flush input buffer, in case there was garbage after a valid menu choice, e.g. "1x"
    flush_input_buffer();
    Last edited by anduril462; 03-07-2014 at 01:26 PM.

  7. #7
    Registered User SiriusWhite's Avatar
    Join Date
    Mar 2014
    Location
    Jamaica
    Posts
    9

    I can't read your mind, or your computer. I can only comment on what you post on this forum. So if your code has changed, then post the updated code -- all of it -- so we can actually help you with your program, instead of working on some older version you aren't using anymore.
    Here is my updated program. I did the corrections that you suggested:

    Code:
    void flush_input_buffer(void)
    {
        int fflush(FILE *ostream);
    }
    
    
    int main ()
    {
    	interface ();
    	info in1;
            MenuData menu[];
    	int password, mmchoice, count=3;
    	enum MenuTime Mchoice;
    
    
    	for (int i=0; i<count; i++)
    	{
    		printf ("\n\t\tEnter Your Cashier Name: ");
    	    scanf ("%s", in1.cashier_name);
    		printf ("\n");
    		printf ("\n\t\tEnter the Password: ");
    		scanf ("%d", &password);
    	
    	    system ("cls");
    	    
           	if (password== PASSWORD)
    		{
    		 	interface ();
    		 	
    		 	FILE *cfPtr;
                if ((cfPtr= fopen ("Food.txt", "a"))==NULL)
             	{
                   printf ("File could not be opened\n");
             	}
             	
    	 	    printf ("\n");
    		    printf ("Enter the Client's name\n:");
    		    scanf ("%s", in1.client_name);
    
    
                printf ("Enter the Client's Table number\n:");
    	        scanf ("%d", &in1.customer_num);
    	        
    
    
    	        fprintf (cfPtr, "\n");
    	        fprintf (cfPtr, "Customer Name: %s\n", in1.client_name);
    	        fprintf (cfPtr, "Table Number: %d\n", in1.customer_num);
    	        
    	        
    		    while (1)
    		 	{ 
    	            
    	            system ("cls");
                	interface ();
                	printf ("\n");
                    printf ("---------------#Welcome to Main Menu#----------------\n");
                    printf ("\n");
                    printf ("\tPress 1 for the Breakfast Menu\n");
                    printf ("\tPress 2 for the Lunch Menu\n");
                    printf ("\tPress 3 for the Dinner Menu\n");
                    printf ("\tPress 4 for the Desert Menu\n");
                    printf ("\tPress 5 for the Beverage Menu\n");
                    printf ("\tPress 6 to Exit\n");
                    scanf ("%d", &Mchoice);
     	
                	switch (Mchoice) 
    				{	
    					case Breakfast:		
    					    system ("cls");
    					    printf ("\t.........Breakfast Menu............\n");
    						displayMenu(breakfast, NUM_BREAKFAST_ITEMS);
    						orderFunction (breakfast, NUM_BREAKFAST_ITEMS);
    						getch ();
            	    		break;
     	  		
                 		case Lunch:
                 			system ("cls");
                 			printf ("\t.........Lunch Menu..........\n");
                		    displayMenu(lunch, NUM_LUNCH_ITEMS);
                		    orderFunction (lunch, NUM_LUNCH_ITEMS);
                		    getch ();
                		    break;
    			
                		case Dinner:
                			system ("cls");
                			printf ("\t.........Dinner Menu.........\n");
                		    displayMenu (dinner, NUM_DINNER_ITEMS);
                		    orderFunction (dinner, NUM_DINNER_ITEMS);
                		    getch ();
                			break;
    				
                		case Dessert:
                		    system ("cls");
                		    printf ("\t.........Desseert Menu.........\n");
                 			displayMenu (dessert, NUM_DESSERT_ITEMS);
                 			orderFunction (dessert, NUM_DESSERT_ITEMS);
                 			getch ();
                			break;
    				
                		case Beverage:
               				system ("cls");
               				printf (".........Beverage Menu........\n");
               			    displayMenu (beverage, NUM_BEVERAGE_ITEMS);
               			    orderFunction (beverage, NUM_BEVERAGE_ITEMS);
               			    getch ();
               				break;
               	
               			case Receipt:
                          	printReceipt (menu, NUM_BREAKFAST_ITEMS);
               				break;
               				
                		case Exit:	
    					    exit (1);
    						break;
    	
    				
               			default:
             	            printf ("This Option Doesn't Exist\n");
               	    	   break;
    						  	
    				    flush_input_buffer();
        	        } // End Switch
        	        	
    	    	 }//End while
                 
            }//End if
             
             else
    		
    		printf ("Invalid Password!\n");
    		count=count-1;
    		printf ("You have %d tries left!\n", count);
    		
        }//End For
        	
    	printf ("This program will close.\n");
    	printf ("\n");
    
    
      
      return 0;  
    } // end main
    
    
    
    
    
    
    void interface ()
    {	
    	 printf ("\t Welcome to Master's Restaurant and Bar!\n");
         printf ("\n");
    	
    	  printf ("                                          o8             \n");        
          printf ("                                          888            \n");             
          printf ("        ooo. .oo. .ooo.      ooo d8b      888oooo.       \n"); 
          printf ("        888P'Y88bP'Y88b      888''8p      d88' `88b      \n"); 
          printf ("        888   888   888      888          888   888      \n");   
          printf ("        888   888   888      888          888   888      \n");
          printf ("       o888o o888o o888o    d888b         `Y8bod8P'      \n");
     
    }//End of Interface
    
    
    
    
    int orderFunction (const MenuData menu[], int numofitems)
    {
    	enum options choices;
    	int i;
    	int qty;
    	
    	printf ("Enter Choice: ");
    	scanf ("%d", &choices);
    	
    	if (choices==0|| choices > numofitems)
    	{
           printf ("Invalid Option.\nPress any key to return to Main Menu.");
    	}
    	
    	flush_input_buffer();
    	
    	printf ("Enter Quantity: ");
    	scanf ("%d", &qty);
    	
    	FILE *cfPtr;
        if ((cfPtr= fopen ("Food.txt", "a"))==NULL)
       	{
           printf ("File could not be opened\n");
       	}
     	  	                 	
         if  (choices== opt1 || choices== opt2 || choices== opt3|| choices== opt4 || choices==opt5 || choices== opt6)
         {                 	  
            fprintf (cfPtr, "Prepare: %s\n", menu[choices-1].prepare[0]);
            if (strlen(menu[choices-1].prepare[1]) > 0 )
            fprintf (cfPtr, "%s\n", menu[choices-1].prepare[1]);
            fprintf (cfPtr, "________________________________________________");
            fprintf (cfPtr, "________________________________________________\n");
        }
        flush_input_buffer();
        
        fclose (cfPtr);
        
        return qty;
        
    }//End of Function
    
    
    
    
    float subtotal (const MenuData menu[], int qty, int numofitems)
    {
    	
    	int i;
    	float subtot;
    
    
    	for(i=0; i<numofitems; i++)
    	{
    	 	subtot= subtot + (menu[i].price*qty);
    	}
    	 
    	return subtot; 
    }
    
    
    void Caltotal (float subtot)
    {
    	float total;
    
    
    	total= subtot* TAX;
    
    
    }
    
    
    void printReceipt (const MenuData menu[], int numofitems)
    {
    	int i;
    	float cash_tender;
    	float change;
    	
    	system ("cls");
    	
        printf ("                      8         \n");
    	printf ("                      88        \n");
    	printf ("                      88ooo.    \n");
        printf (" oo. .o. .oo   oo d8b d8'  `8b  \n");
        printf (" 88P'Y88'Y88   88'    88    88  \n");
        printf ("o88o     o88o d88b    `YbodP'  \n");
    	printf ( "\n");
    	printf ("        ** RECIEPT**           \n");
    	printf ("\n");
    	printf ("\n");
    	printf ("5 Kingston Road, Lot 5\n");
    	printf ("\n");
    	printf ("\n");
    	printf ("Item Bought      QTY        Price\n");
        
        for(i=0; i<numofitems; i++)
        {
            printf ("%s \t$ %.2f\n", menu[i].name,  menu[i].price);
            printf ("Subtotal                $ %.2f\n", subtotal (menu, qty, numofitems)); //I keep getting qty as an error. Even if I pass it, I get an error. 
            printf ("TAX                     $ %.2f\n", Caltotal (subtot));
            printf ("Toatl Sale              $ %.2f\n", Caltotal (subtot));
            printf ("\n");
        }
        
    	printf ("Enter the cash tendered by customer: ");
    	scanf ("%f", &cash_tender);
    	
    	change= total-ctender;
    	printf ("The change id %.2f", change);
    	
    	flush_input_buffer();	
    }

    I did the calculation is separate functions and called it when I was printing it in the receipt, because calling the results to the printReceipt function was not working.

  8. #8
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    That's not your complete program. You're leaving out all the struct definitions, and all the headers (#include directives), plus all your constant definitions. Please provide those, I don't feel like guessing what they are.

    I notice, right at the top, that you did not write flush_input_buffer correctly. I gave you a link to a page with an example you could copy-paste. The red text in my post above are links. Read them all. The flush operation you want is the while loop that calls getchar. That one line (with the associated definition for ch) is all you need. That will actually flush the input buffer.

  9. #9
    Registered User SiriusWhite's Avatar
    Join Date
    Mar 2014
    Location
    Jamaica
    Posts
    9
    Quote Originally Posted by anduril462 View Post
    That's not your complete program. You're leaving out all the struct definitions, and all the headers (#include directives), plus all your constant definitions. Please provide those, I don't feel like guessing what they are.
    Code:
     # include <conio.h># include <stdio.h>
    # include <stdlib.h>
    # include <string.h>
    
    
    #define PASSWORD 161996
    #define TEXTSIZE  80
    #define TAX 0.01
    #define NUM_BREAKFAST_ITEMS  3
    #define NUM_LUNCH_ITEMS 3
    #define NUM_DINNER_ITEMS 3  
    #define NUM_DESSERT_ITEMS 6
    #define NUM_BEVERAGE_ITEMS 6
     
    struct MenuData {
      char  name[TEXTSIZE];
      char  desc[2][TEXTSIZE];
      char  prepare[2][TEXTSIZE];
      float price;
    };
    
    
    typedef struct MenuData MenuData;
    
    
    
    
    /*Initialization of array elements MenuData*/
    
    
    const MenuData breakfast[NUM_BREAKFAST_ITEMS] = {
    
    
      {"Egg Breakfast", "Two eggs with a side of bacon and two slices of toast.", "", "2 Eggs, 2 Toats, 2 Bacons", "", 250.00},
    
    
      {"Pancake Breakfast", "Three Buttermilk pancakes, butter and syrup.", "", "Three Pancakes, Butter, Syrup", "", 200.00},
    
    
      {"Meat Variety", "Three eggs, bacon and", "smoked sausages,porridge, three fried dumplings and jam.", "1 Bowl Poridge,", "3 Fried Dumplings, Jam", 350.00}
    
    
    };
    
    
    const MenuData lunch[NUM_LUNCH_ITEMS]= {
    	
    	{"Cheese Burger", " Thick-sliced bacon and two slices of tastee", "cheese served with seared buns and fries.", "Cheese Burger, Fries", "", 450.00,},
    	
    	{"Hotdog N' Fries", "Smoked sausages, Hotdog Rolls with seasoned Fries.", "", "Smoked Sausage Hotdog, Seasoned Fries", "", 345.60,},
    	
    	{"Chicken Feet Soup", "Chicken feet soup, with boiled dumplings", "yellow yam, sweet potato and 5 slices garlic bread.", "Chicken soup- Boiled Dumplings, Yellow", "Yam, Sweet Potato, 5 Garlic Bread", 445.60}
    	
    };
    
    
    const MenuData dinner [NUM_DINNER_ITEMS]= {
    	{"Sunday Dinner", "Fried Chicken served with rice and peas and macaroni salad", "", "Fried Chicken, Rice and Peas, Macaroni Salad", "", 600.00,},
    	
    	{"Pastas N' Such", "Macaroni casserole topped with an assortment of cheese","served with mashed potatoes and baked chicken", "Macaroni Casserole, Four Cheese Topping", "Mashed Potatoes, Baked Chicken", 450.00,},
    	
    	{"Real Jamaican Dinner", "Ackee and saltfish served with boiled dumplings", "yam and irish potatoes", "Ackee and Saltfish, Boiled dumplings, Yam", "", 395.00,}
    };
    
    
    const MenuData dessert [NUM_DESSERT_ITEMS]= {
    	{"Rock Cakes","", "", "Rock Cakes", "", 70.00,},
    	
    	{"Gizzarda", "", "", "Gizzarda", "", 95.50,},
    	
    	{"Fruit Cake", "", "", "Fruit Cake", "", 200.00,},
    	
    	{"Apple Pie Slice", "", "", "Apple Pie Slice", "", 300.00,},
    	
    	{"Cheese Cake Slice", "","", "Cheese Cake Slice", "", 300.00,},
    	
    	{"Fudge Cupcake", "","", "Fudge Cupcake", "", 100.00,}
    	
    };
    
    
    const MenuData beverage [NUM_BEVERAGE_ITEMS]= {
    	{"Hot Chocolate", "", "", "Hot Chocolate", "", 60.00,},
    	
    	{"Coffee", "", "", "Coffee", "", 50.00,},
    	
    	{"Soft Drink", "", "", "Soft Drink", "", 90.00,},
    	
    	{"Beer", "", "", "Beer", "", 150.00,},
    	
    	{"Wine", "", "", "Wine", "", 250.00,},
    	
    	{"Water", "", "", "Water", "", 75.00,}
    	
    };
    
    
    /*End of initialization*/
    
    
    
    
    struct customerInfo {
    	int customer_num;
    	char cashier_name[20], client_name[20];
    }; typedef struct customerInfo info;
     
    /*Fuction Declarations*/ 
    void interface (); 
    int orderFunction (const MenuData menu[], int);
    float Subtotal (const MenuData menu[], int, int);
    void Caltotal (float);
    void printReceipt (const MenuData menu[], int, float);
    
    
    
    
    enum options {
    	opt1= 1,
    	opt2= 2,
    	opt3= 3,
    	opt4= 4,
    	opt5= 5,
    	opt6= 6
    };
    
    
    enum MenuTime {
        Breakfast=1, 
    	Lunch=2,
    	Dinner=3,
    	Dessert=4,
    	Beverage=5,
    	Receipt=6,
    	Exit=7
    };
    
    
    /* display any menu data */
    
    
    void displayMenu(const MenuData menu[], int numofitems)
    {
      int i;
      printf("\n");
      for(i=0; i<numofitems; i++) {
        printf("%d. %s \n",       i+1, menu[i].name);
        printf("Description: %s \n",   menu[i].desc[0]);
        if( strlen(menu[i].desc[1]) > 0 )
        printf("%s \n",              menu[i].desc[1]);
        printf("Price: $%.2f \n",      menu[i].price);
        printf("\n");
      }
    }
    
    
    int main ()
    {
    	interface ();
    	info in1;
    	int ch;
    	MenuData menu;
    	int password, mmchoice, count=3;
    	enum MenuTime Mchoice;
    
    
    	for (int i=0; i<count; i++)
    	{
    		printf ("\n\t\tEnter Your Cashier Name: ");
    	    scanf ("%s", in1.cashier_name);
    		printf ("\n");
    		printf ("\n\t\tEnter the Password: ");
    		scanf ("%d", &password);
    	
    	    system ("cls");
    	    
           	if (password== PASSWORD)
    		{
    		 	interface ();
    		 	
    		 	FILE *cfPtr;
                if ((cfPtr= fopen ("Food.txt", "a"))==NULL)
             	{
                   printf ("File could not be opened\n");
             	}
             	
    	 	    printf ("\n");
    		    printf ("Enter the Client's name\n:");
    		    scanf ("%s", in1.client_name);
    
    
                printf ("Enter the Client's Table number\n:");
    	        scanf ("%d", &in1.customer_num);
    	        
    
    
    	        fprintf (cfPtr, "\n");
    	        fprintf (cfPtr, "Customer Name: %s\n", in1.client_name);
    	        fprintf (cfPtr, "Table Number: %d\n", in1.customer_num);
    	        
    	        
    		    while (1)
    		 	{ 
    	            
    	            system ("cls");
                	interface ();
                	printf ("\n");
                    printf ("---------------#Welcome to Main Menu#----------------\n");
                    printf ("\n");
                    printf ("\tPress 1 for the Breakfast Menu\n");
                    printf ("\tPress 2 for the Lunch Menu\n");
                    printf ("\tPress 3 for the Dinner Menu\n");
                    printf ("\tPress 4 for the Desert Menu\n");
                    printf ("\tPress 5 for the Beverage Menu\n");
                    printf ("\tPress 6 to Exit\n");
                    scanf ("%d", &Mchoice);
     	  
     	            while ((ch = getchar()) != '\n' && ch != EOF);
     	            
                	switch (Mchoice) 
    				{	
    					case Breakfast:		
    					    system ("cls");
    					    printf ("\t.........Breakfast Menu............\n");
    						displayMenu(breakfast, NUM_BREAKFAST_ITEMS);
    						orderFunction (breakfast, NUM_BREAKFAST_ITEMS);
    						getch ();
            	    		break;
     	  		
                 		case Lunch:
                 			system ("cls");
                 			printf ("\t.........Lunch Menu..........\n");
                		    displayMenu(lunch, NUM_LUNCH_ITEMS);
                		    orderFunction (lunch, NUM_LUNCH_ITEMS);
                		    getch ();
                		    break;
    			
                		case Dinner:
                			system ("cls");
                			printf ("\t.........Dinner Menu.........\n");
                		    displayMenu (dinner, NUM_DINNER_ITEMS);
                		    orderFunction (dinner, NUM_DINNER_ITEMS);
                		    getch ();
                			break;
    				
                		case Dessert:
                		    system ("cls");
                		    printf ("\t.........Desseert Menu.........\n");
                 			displayMenu (dessert, NUM_DESSERT_ITEMS);
                 			orderFunction (dessert, NUM_DESSERT_ITEMS);
                 			getch ();
                			break;
    				
                		case Beverage:
               				system ("cls");
               				printf (".........Beverage Menu........\n");
               			    displayMenu (beverage, NUM_BEVERAGE_ITEMS);
               			    orderFunction (beverage, NUM_BEVERAGE_ITEMS);
               			    getch ();
               				break;
               	
               			case Receipt:
                          	printReceipt (menu, numofitme, subtot);
               				break;
               				
                		case Exit:	
    					    exit (1);
    						break;
    	
    				
               			default:
             	            printf ("This Option Doesn't Exist\n");
               	    	   break;
    						  	
    				    
        	        } // End Switch
        	        	
    	    	 }//End while
                 
            }//End if
             
             else
    		
    		printf ("Invalid Password!\n");
    		count=count-1;
    		printf ("You have %d tries left!\n", count);
    		
        }//End For
        	
    	printf ("This program will close.\n");
    	printf ("\n");
    
    
      
      return 0;  
    } // end main
    
    
    
    
    
    
    void interface ()
    {	
    	 printf ("\t Welcome to Master's Restaurant and Bar!\n");
         printf ("\n");
    	
    	  printf ("                                          o8             \n");        
          printf ("                                          888            \n");             
          printf ("        ooo. .oo. .ooo.      ooo d8b      888oooo.       \n"); 
          printf ("        888P'Y88bP'Y88b      888''8p      d88' `88b      \n"); 
          printf ("        888   888   888      888          888   888      \n");   
          printf ("        888   888   888      888          888   888      \n");
          printf ("       o888o o888o o888o    d888b         `Y8bod8P'      \n");
     
    }//End of Interface
    
    
    
    
    int orderFunction (const MenuData menu[], int numofitems)
    {
    	enum options choices;
    	int i, ch;
    	int qty;
    	
    	while ((ch = getchar()) != '\n' && ch != EOF);
    	printf ("Enter Choice: ");
    	scanf ("%d", &choices);
    	
    	if (choices==0|| choices > numofitems)
    	{
           printf ("Invalid Option.\nPress any key to return to Main Menu.");
    	}
    	
    	
    	printf ("Enter Quantity: ");
    	scanf ("%d", &qty);
    	
    	FILE *cfPtr;
        if ((cfPtr= fopen ("Food.txt", "a"))==NULL)
       	{
           printf ("File could not be opened\n");
       	}
     	  	                 	
         if  (choices== opt1 || choices== opt2 || choices== opt3|| choices== opt4 || choices==opt5 || choices== opt6)
         {                 	  
            fprintf (cfPtr, "Prepare: %s\n", menu[choices-1].prepare[0]);
            if (strlen(menu[choices-1].prepare[1]) > 0 )
            fprintf (cfPtr, "%s\n", menu[choices-1].prepare[1]);
            fprintf (cfPtr, "________________________________________________");
            fprintf (cfPtr, "________________________________________________\n");
        }
       
        
        fclose (cfPtr);
        
        return qty;
        
    }//End of Function
    
    
    
    
    float Subtotal (const MenuData menu[], int qty, int numofitems)
    {
    	
    	int i;
    	float subtot=0.00;
    	float price1;
    
    
    	for(i=0; i<numofitems; i++)
    	{
    		price1= menu[i].price*qty;
    	 	
    	}
    	subtot= subtot + price1;
    	return subtot; 
    }
    
    
    void Caltotal (float subtot)
    {
    	float total;
    
    
    	total= subtot* TAX;
    
    
    }
    
    
    void printReceipt (const MenuData menu[], int numofitems, float subtot)
    {
    	int i;
    	float cash_tender;
    	float change;
    	
    	system ("cls");
    	
        printf ("                      8         \n");
    	printf ("                      88        \n");
    	printf ("                      88ooo.    \n");
        printf (" oo. .o. .oo   oo d8b d8'  `8b  \n");
        printf (" 88P'Y88'Y88   88'    88    88  \n");
        printf ("o88o     o88o d88b    `YbodP'  \n");
    	printf ( "\n");
    	printf ("        ** RECIEPT**           \n");
    	printf ("\n");
    	printf ("\n");
    	printf ("5 Kingston Road, Lot 5\n");
    	printf ("\n");
    	printf ("\n");
    	printf ("Item Bought             Price\n");
        
        for(i=0; i<numofitems; i++)
        {
            printf ("%s \t$ %.2f\n", menu[i].name,  menu[i].price);
            printf ("Subtotal                $ %.2f\n", subtot;
            printf ("TAX                     $ %.2f\n", Caltotal (subtot));
            printf ("Toatl Sale              $ %.2f\n", Caltotal (subtot));
            printf ("\n");
        }
        
    	printf ("Enter the cash tendered by customer: ");
    	scanf ("%f", &cash_tender);
    	
    	change= total-ctender;
    	printf ("The change id %.2f", change);
    		
    }
    Here is the whole program. I changed flush operation to the while loop.

  10. #10
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Is there a reason you never save the return value of orderFunction?
    (Note, I might have missed a few times; the code is very long.)

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  11. #11
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Did you try compiling that program. I get several errors and quite a few warnings when I tried.

    main.c|35|warning: missing braces around initializer [-Wmissing-braces]|
    main.c|35|warning: (near initialization for ‘breakfast[0].desc’) [-Wmissing-braces]|
    main.c|49|warning: missing braces around initializer [-Wmissing-braces]|
    main.c|49|warning: (near initialization for ‘lunch[0].desc’) [-Wmissing-braces]|
    main.c|59|warning: missing braces around initializer [-Wmissing-braces]|
    main.c|59|warning: (near initialization for ‘dinner[0].desc’) [-Wmissing-braces]|
    main.c|68|warning: missing braces around initializer [-Wmissing-braces]|
    main.c|68|warning: (near initialization for ‘dessert[0].desc’) [-Wmissing-braces]|
    main.c|84|warning: missing braces around initializer [-Wmissing-braces]|
    main.c|84|warning: (near initialization for ‘beverage[0].desc’) [-Wmissing-braces]|
    main.c|143|warning: no previous declaration for ‘displayMenu’ [-Wmissing-declarations]|
    main.c||In function ‘main’:|
    main.c|217|warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘enum MenuTime *’ [-Wformat=]|
    main.c|264|error: ‘numofitme’ undeclared (first use in this function)|
    main.c|264|note: each undeclared identifier is reported only once for each function it appears in|
    main.c|264|error: ‘subtot’ undeclared (first use in this function)|
    main.c|264|error: incompatible type for argument 1 of ‘printReceipt’|
    main.c|114|note: expected ‘const struct MenuData *’ but argument is of type ‘MenuData’|
    main.c|164|warning: unused variable ‘mmchoice’ [-Wunused-variable]|
    main.c||In function ‘orderFunction’:|
    main.c|330|warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘enum options *’ [-Wformat=]|
    main.c|332|warning: comparison between signed and unsigned integer expressions [-Wsign-compare]|
    main.c|325|warning: unused variable ‘i’ [-Wunused-variable]|
    main.c||In function ‘Caltotal’:|
    main.c|386|warning: variable ‘total’ set but not used [-Wunused-but-set-variable]|
    main.c||In function ‘printReceipt’:|
    main.c|421|error: expected ‘)’ before ‘;’ token|
    main.c|425|error: expected ‘;’ before ‘}’ token|
    main.c|430|error: ‘total’ undeclared (first use in this function)|
    main.c|430|error: ‘ctender’ undeclared (first use in this function)|
    ||=== Build finished: 7 errors, 17 warnings (0 minutes, 1 seconds) ===|
    Jim

  12. #12
    Registered User SiriusWhite's Avatar
    Join Date
    Mar 2014
    Location
    Jamaica
    Posts
    9
    Yes, I did compile it, but my Dev doesn't describe the errors to me when I get one, so I basically have to figure them out on my own. Thanks for showing me them though!

  13. #13
    Registered User SiriusWhite's Avatar
    Join Date
    Mar 2014
    Location
    Jamaica
    Posts
    9
    My program runs fine when I comment out the function call for printReceipt in main (line 263)... I'll just have to try harder

  14. #14
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by SiriusWhite View Post
    Yes, I did compile it, but my Dev doesn't describe the errors to me when I get one, so I basically have to figure them out on my own. Thanks for showing me them though!
    Your program can not compile successfully since you have actual errors in it, along with several warnings. I'll explain some of them to you:
    The "missing braces" warnings have to do with your menu definitions. Every time you are initializing a sub-component of an aggregate type*, you need a new set of braces. An aggregate type is something that combines several things of same or different types. An array combines several things of the same type. A struct or union combines several things of (possibly) different types. So each menu type is an array of structs. You have the correct braces for this. But each struct has two arrays in it (desc and prepare) that are themselves arrays of two char arrays (strings) each, so they need their own set of braces:
    Code:
    const MenuData breakfast[NUM_BREAKFAST_ITEMS] = {
        {   "Egg Breakfast",
            {   "Two eggs with a side of bacon and two slices of toast.",
                ""
            },
            {   "2 Eggs, 2 Toats, 2 Bacons",
                ""
            },
            250.00
        },
    ...
    };
    Note that I use indentation along with the braces to further show the breakdown of the object being initialized. Also, I avoid the 200+ char lines that are hard to read and easy to screw up. Using more space in your source file is a good thing, whenever it improves readability or maintainability of your code.

    The "%d" format specifier requires 'int *', not 'enum MenuTime *' type is because enum types are distinct from int types.
    Quote Originally Posted by C11 standard, 6.7.2.2 p4
    Each enumerated type shall be compatible with char, a signed integer type, or an
    unsigned integer type. The choice of type is implementation-defined,
    What that means is an enum type may not be the same size as an int. If they're smaller, scanf may overwrite memory that is not part of the enum type, causing undefined behavior (just as if you passed in a char * instead of an int *). Read it into an int variable and if it's a valid value, assign it to Mtype
    Code:
    scanf("%d", &some_int_var);
    if (some_int_var is NOT a valid enum value)
        input error
    else
        Mtype = some_int_var
    Note, in your code, you should check the return value of scanf and handle non-numeric data appropriately (or use fgets+sscanf) as I mentioned in post #6.

    You have several undeclared variables and variables that you mis-typed in places (menuitme instead of menuitem).

    You are missing a parenthesis in printReceipt on this line:
    Code:
    printf ("Subtotal                $ %.2f\n", subtot;
    There are several other related syntax and declaration errors you need to fix -- fairly basic things -- before you need to worry about running this program.
    Quote Originally Posted by SiriusWhite View Post
    My program runs fine when I comment out the function call for printReceipt in main (line 263)... I'll just have to try harder
    As noted with the above issues, it does not compile/run fine. Turn up the warning level on your compiler (read the documentation) and fix everything.

    Also, as I noted before, I ran into issues with conio.h and getch(). You don't really need conio.h, you can replace all the getch() calls with getchar() (which is in stdio.h, which everybody has).

    Lastly, your code is mostly indented correctly, but there are still some issues. Use the auto-indent feature of your editor to clean it up before posting. Besides, it helps find missing brackets, parentheses, etc and can also help you align initializers of complicated data types. Readability is crucial.


    * There is one exception: char arrays being initialized as strings. In that case, the string literal does not need braces around it.

  15. #15
    Registered User SiriusWhite's Avatar
    Join Date
    Mar 2014
    Location
    Jamaica
    Posts
    9
    Thank you for the advice, I haven't been able to come online because of a stomach flu, but I'm back now!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help in passing structure elements through function
    By kriss332 in forum C Programming
    Replies: 2
    Last Post: 09-22-2013, 08:27 AM
  2. Replies: 3
    Last Post: 03-14-2013, 03:25 PM
  3. Access vector<structure> elements in a function, how?
    By KeithS in forum C++ Programming
    Replies: 5
    Last Post: 10-25-2011, 10:56 AM
  4. MPI_Scatter structure elements
    By Chris_1980 in forum C Programming
    Replies: 0
    Last Post: 06-30-2010, 04:46 AM
  5. Calling of function within a structure
    By saswatdash83 in forum C Programming
    Replies: 1
    Last Post: 06-09-2009, 01:16 PM