Alif Khair Alif Khair - 3 months ago 26
C Question

C programming TEXT FILE not reading whole line

Here is the input from TEXT FILE :

19 BISON-BURGER 10 15.000000
10 BRAISED-COD 5 17.000000
23 MOJITO 8 11.000000
3 IRISH-COFEE 6 2.300000
7 LAMB-SHOULDER 8 23.000000


The output came out from compiler after input being key in was :

10 BRAISED-COD 5 17.000000
3 IRISH-COFEE 6 2.300000
7 LAMB-SHOULDER 8 23.000000


Why the compiler skipping some of the lines ? Is there any changes I need to make?

Please help. Thank you so much.

Here is the full code :

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>

struct product
{
int quantity, reorder, i, id;
char name[20];
float price;
};

int main()
{
FILE * fp;

int i=0;
struct product a;
system("cls");

char checker;

do
{
fp = fopen("addproduct.txt","a+t");
system("cls");

printf("Enter product ID : ");
scanf(" %d", &a.id);

printf("Enter product name : ");
scanf(" %s", a.name);

printf("Enter product quantity : ");
scanf(" %d", &a.quantity);

printf("Enter product price : ");
scanf(" %f", &a.price);


fprintf(fp, "%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
printf("Record saved!\n\n");

fclose(fp);

printf("Do you want to enter new product? Y / N : ");

scanf(" %c", &checker);
checker = toupper(checker);

i++;

system("cls");
}

while(checker=='Y');



if(checker == 'N')
{
fp = fopen("addproduct.txt","r");

while(fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price)==4)
{
fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price);
printf("%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
}

fclose(fp);

}


return(0);
}

Answer

You're reading two lines from the file on each iteration of the output loop. Get rid of the extra scanf:

    while(fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price)==4)
    {
        printf("%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
    }