简体   繁体   中英

Accepting Multiple Strings in 2 dimensional array?

While executing this, loop is directly jumping to the end and giving me below output.

1.Generate Bill

2.Generate Bills of last 10 Purchase

Select Option:1

Enter Number of Groceries:3

Enter GroceryName:XYZ <Hit Enter>

Enter GroceryName:

Enter GroceryName:

Could you please suggest me better way of doing it in c ? I have already tried certain links on stack overflow on this, however it doesn't seem to be working for me.

void main()
{
    int iPrice[1000];
    char cGroceName[100][100];
    int iOption;
    int iGrocNum;

    printf("\n1.Generate Bill");
    printf("\n2.Generate Bills of last 10 Purchase");
    printf("\nSelect Option:");
    scanf_s("%d", &iOption);

    switch (iOption)
    {
    case 1:
        printf("\nEnter Number of Groceries:");
        scanf_s("%d",&iGrocNum);
        for (int i = 0; i <iGrocNum; i++)
        {  

            printf("\nEnter GroceryName:");
            scanf_s(" %s",cGroceName[i]);

        }
scanf_s(" %s",cGroceName[i]);

should be

scanf_s("%99s", cGroceName[i], sizeof cGroceName[i]);

as scanf_s requires a third argument for certain format specifiers such as %s denoting the maximum size of its corresponding argument.

See scanf_s documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM