Manoz Biswas Manoz Biswas -3 years ago 125
C Question

How to read the list of number in c

I have a file which includes product name, product quantity and product price in the following format.


Product Qty Price
Tv 2 10
Mobile 3 20
Computer 5 30

I want to read the number of products from the integer (such as 3) given above the product list and count the total price of the products. The program will use struct to read the product details such as

struct product {
Char name[30];
int qty ;
float price;

What are the best practices to make this program easier?

Answer Source

Please try if the following program can help you.

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

struct product {
    char name[30];
    int qty;
    float price;

int main(void) {
    int count = 0;
    char line[100];
    FILE *fptr;
    fptr = fopen("file.txt", "r");
    fscanf(fptr, "%d", &count); // count = 3
    struct product *p = malloc(sizeof(struct product));
    int i = 0;
    double sum = 0;
    while (i < count + 2 && fgets(line, sizeof(line), fptr) != NULL) {
        if (i > 1) {
            sscanf(line, "%s %d %f\n", (*p).name, &(*p).qty, &(*p).price);
            sum = sum + (*p).price;
    printf("sum: %f\n", sum);
    return 0;


$ gcc main.c                                                                   
$ ./a.out                                                                      
sum: 60.000000
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download