Using C, write a set of functions using dynamic arrays that will represent a vid
ID: 3568436 • Letter: U
Question
Using C, write a set of functions using dynamic arrays that will represent a video game store inventory.
1. The program should open the first file name given on the command line (NOT stdin). The file will contain a list of the format (name, price, number in stock ). For example:
A sample program execution is:
There can be any number of games in the file. Make sure your dynamic arrays can shrink and grow to fit the data.
2. In the file, dynamicarray.c, write the code necessary to complete the assignment.
(a) The program should first print the inventory with numbers and a command prompt:
(b) When the user types a number, it should subtract 1 from the number in stock for that game. For example:
COMMAND: 2
would result in the following output:
The number of in stock for a game cannot go below 0. If the user tries to remove a game that has 0 stock, the program should print an error message. For example if Left for Dead had 0 stock, it would print:
(c) When the user types
Explanation / Answer
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *fp = fopen(arg[1], "r");
const char s[2] = ", ";
char *token;
int i;
int count = 0;
char line[20];
char * name[20],ch;
int price[20];
int quantity[20];
if(fp != NULL && argc == 3)
{
while(fgets(line, sizeof line, fp) != NULL)
{
token = strtok(line, s);
printf("%s ",token);
name[count] =token;
token = strtok(NULL,s);
price[count] = atof(token);
printf("%f ",atof(token));
token = strtok(NULL,s);
quantity[count] = atoi(token);
printf("%d ",atoi(token));
count++;
}
do
{
printInventor(name,price,quantity,count);
printf(" Command");
scanf("%d",&cmd);
if(quantity[cmd] > 0)
quantity[cmd] --;
else
{
printf("Error : 3 %s IS OUT OF STOCK",name[cmd]);
}
printf(" Enter q to Quit / y to not Quit");
ch = getch();
}while(ch != 'q');
saveInventory(arg[2],name,price,quantity,count;
fclose(fp);
}
else {
perror("user.dat");
}
return 0;
}
void printInventory(char * names[],int price[], int quantity[], int count)
{
int i=0;
for(i=0;i<count;i++)
{
printf(" %s %f %d",names[i],price[i],quantity[i]);
}
}
void saveInventory(char * fileName,char * names[],int price[], int quantity[], int count)
{
int i=0;
int n;
FILE *fptr;
fptr=fopen("fileName","w");
if(fptr==NULL)
{
printf("Error!");
exit(1);
}
for(i=0;i<count;i++)
{
fprintf(" %s %f %d",names[i],price[i],quantity[i]);
}
fclose(fptr);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.