Home > database >  Creating a restaurant menu system using a 2d array of strings and integers in C
Creating a restaurant menu system using a 2d array of strings and integers in C

Time:12-26

Let's say I wanted to create sort of a "menu system" for a restaurant. I'm pretty sure you'd use a 2d array for this, although combining strings AND integers into one array gave me some trouble. The program tries it's best and prints out the first couple of characters correct, then it gives up and just starts fumbling with numbers.

Here's the code and a screenshot of the output:

// Import libraries
#include<stdio.h>
#include<stdlib.h>
// Initialize main function
void main()
{   // Beginning of code

    char menuOfItems[6][25][6] =
    {{
        "Pizza",
        "Fish fillet",
        "Vegetable soup"
        "Ice Cream",
        "Coca Cola",
        "Mineral water",
    },
    {
        45,
        50,
        40,
        25,
        15,
        10
    }};

    for(int i = 0; i < 6; i  )
    {
        printf("%s -- %d\n",menuOfItems[i][i]);
    }

}   // End of code

and as promised, here's the screenshot

CodePudding user response:

Actually, you created not 2d-array, but 3d-array and trying to print it's diagonal. Also you've forgot comma after "Vegetable soup" item. It would be better to use array of structs in this case:

// Import libraries
#include<stdio.h>
#include<stdlib.h>
// Initialize main function
void main()
{   // Beginning of code
    //
    struct menuItem {
            char m_name[26];
            int m_price;
    };

    struct menuItem menuOfItems[6]=
    {
            {"Pizza",45},
            {"Fish fillet", 50},
            {"Vegetable soup", 40},
            {"Ice Cream", 25},
            {"Coca Cola", 15},
            {"Mineral water", 10}
    };

    for(int i = 0; i < 6; i  )
    {
        printf("%s -- %d\n", menuOfItems[i].m_name, menuOfItems[i].m_price);
    }

}   // End of code

CodePudding user response:

Arrays are homogeneous in C - they can only contain elements of a single type.

That type, however, can be an aggregate type such as a struct.

Consider the following:

#include <stdio.h>

struct item {
    char name[128];
    unsigned value;
};

int main(void)
{
    struct item menu[] = {
        { "Pizza", 45 },
        { "Fish fillet", 50 },
        { "Vegetable soup", 40 },
        { "Ice Cream", 25 },
        { "Coca Cola", 15 },
        { "Mineral water", 10 }
    };

    size_t length = sizeof menu / sizeof *menu;

    for (size_t i = 0; i < length; i  )
        printf("%s - %u\n", menu[i].name, menu[i].value);
}
Pizza - 45
Fish fillet - 50
Vegetable soup - 40
Ice Cream - 25
Coca Cola - 15
Mineral water - 10
  • Related