In: Computer Science
A small grocery store uses a very basic file format to store prices for its goods. This file format has one item per line. The first word of the line is the name of the product, and after this is the price of the product in dollars (no dollar sign). For example, a typical file might look like:
bread 2.50
milk 1.90
pizza 10.95
Write a C program which reads one such file (create your own for testing) into two arrays, one called “items” which stores the product names, and the other called “prices” which stores all the prices. When creating the arrays, assume that the maximum length of a product name should be capped at 100 characters, and that there is a maximum of 1000 products in the file. Once all values are stored in the array, print the product list to the screen, including dollar signs in the prices as necessary along with headers for each column, for example:
ITEM PRICE
==============
bread $2.50
milk $1.90
pizza $10.95
`Hey,
Note: Brother if you have any queries related the answer please do comment. I would be very happy to resolve all your queries.
Please note there should be Sales.txt file in the same directory as your code. (Mentioned in question)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
struct product
{
char product_name[20];
double unitprice;
};
int main()
{
FILE *fptr, *fp;
struct product products[1000];
if ((fptr = fopen("Sales.txt", "r")) == NULL)
{
printf("Error! opening file");
return 0; /* Program exits if file pointer returns NULL. */
}
char name[100];
double price, total;
int i = 0;
while (fscanf(fptr, "%s %lf", name, &price) == 2)
{
strcpy(products[i].product_name, name);
products[i].unitprice = price;
i++;
}
fclose(fptr);
int kt=0;
printf("ITEM PRICE\n==============\n");
for(kt=0;kt<i;kt++)
{
printf("%s
$%.2f\n",products[kt].product_name,products[kt].unitprice);
}
return 0;
}
Kindly revert for any queries
Thanks.