-3

Figure 1 shows a text file (itemlist.txt) that store item code, item name, item price, and item quantity. Write a program to read the data from the text file and then display the item’s information which with 0 quantity on the screen.

Assume that data stored in the file are:

itemCode            a unique unsigned integer that differentiates an item from another
itemName            the name of an item (not more than 50 characters)
itemPrice           the current selling price of an item
itemQuantity        an integer that shows the quantity of an item               

Also, assume that the fields in the file are separated by a comma.

File content:

 3123,Potato Chips,3.99,8
 2213,Peanut butter,7.99,0
 4533,Candy,1.05,14
 8744,Ice cream,2.50,0

Example output:

 Out-of-stock items:
 -------------------------------
 2213   Peanut butter   7.99
 8744   Ice cream   2.50

Can anyone read my code and see what is the problem? The program abnormally exits, but I don't know why..

#include <stdio.h>
#include <stdlib.h>
 int main()
 {
   unsigned int itemCode;
   char itemName[50];
   float itemPrice;
   int itemQuantity;

   FILE *fp;
   fp = fopen("itemlist.txt", "r");
   printf("%s","Out-of-stock items: \n");
   printf("-------------------------");

   while(!feof(fp)) {
    fscanf(fp, "%4u,%[^,],%f,%d", &itemCode, itemName, &itemPrice, &itemQuantity);

    if(itemQuantity == 0){
        printf("%u %s %f\n",itemCode,itemName,itemPrice);
    }


   }
    fclose(fp);

    return 0;



}

And also I would like to know that if the name of an item is not more than 50 characters, how many elements are there in the itemName array?

Chinmaya B
  • 405
  • 1
  • 7
  • 21
Oliver Sim
  • 19
  • 7

2 Answers2

0

Your main problem is probably not your program, but your environment. I have tested your program and it doesn't crash and it does make the correct output for the file in question. You should check your file permissions or make a new project with the program, then it can work.

Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
0

Your code causes undefined behavior if some input record contains itemName 50 or more characters length, because you are using limited buffer:

char itemName[50];

Maybe it would be better to implement custom parsing, due to scanf() is not flexible enough to meet all your possible inputs.

Sergio
  • 8,099
  • 2
  • 26
  • 52