otboss
otboss

Reputation: 741

Array containing string

Hey I am trying to create an invoice program that is supposed to accept the item name, item price and quantity and store them in a list or array. When I run the program however I get errors. Can someone please help?? I'm noob to c and cannot see how I went wrong, the concept is very simple..

Here is the program:

#include <string.h>
#include <conio.h>

int main()
  {
   char item_name[255];
   float item_price=0;
   float quantity;
   int choice;
   int k;

   for (k=0;choice != 2;k++)
    {
       printf ("Enter item name: ");
       scanf ("%s", item_name[k]);
       printf ("\n");
       printf ("Enter item price: ");
       scanf ("%f", &item_price[k]);
       printf ("\n");
       printf ("Enter item quantity: ");
       scanf ("%f", &quantity[k]);
       printf ("\n\n");
       printf ("Enter another item? Enter '1' for yes and '2' for no: ");
       scanf ("%d", &choice);
    }

  }

these are the errors:

sample.c: In function ‘main’: sample.c:15:8: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=] scanf ("%s", item_name[k]); ^ sample.c:18:32: error: subscripted value is neither array nor pointer nor vector scanf ("%f", &item_price[k]); ^ sample.c:21:30: error: subscripted value is neither array nor pointer nor vector scanf ("%f", &quantity[k]); ^ sample.c:25:5: error: expected ‘;’ before ‘}’ token } ^ sample.c:8:10: warning: variable ‘quantity’ set but not used [-Wunused-but-set-variable] float quantity; ^ sample.c:7:10: warning: variable ‘item_price’ set but not used [-Wunused-but-set-variable] float item_price=0; ^

Upvotes: 1

Views: 122

Answers (1)

4386427
4386427

Reputation: 44246

char item_name[255];

is a single string - not an array of strings.

item_name[k]

is a char - not a char*

So you need to make item_name a 2D array of strings

char item_name[100][255];

and then use

scanf ("%s", item_name[k]);

The next problem is item_price. It also needs to be an array:

float item_price[100];

And same story with float quantity

float quantity[100];

And then your are missing a ";" at the end of the last scanf

Finally you need to add

if (choice == 2) break;

to get out of the loop.

The proposed code allows for 100 items so you should all so add:

if (k > 99) break;

as the first line in the for-loop

Upvotes: 1

Related Questions