0

I have some difficulty in working with files in C. I already know how to read and write files in C but all I can do is just read and append. If I want to read lines of strings and converting them to numbers (int), how would I do it?

for example:

mytextfile.txt contains these data:

12345 30 15
 2111  9 20
  321 17  7

now for each line, I want to use the first number as a variable for price and the next number as quantity and the last number as discount. My problem is how am I going to store the three number on a variable so that I can use them as integers (or string)?

My output should have been the computed amount based on the price, quantity and discount listed down one value(the result) per line...

3

1 Answer 1

0
#define MAXLINE 80

typedef struct {
    double cost, qty, disc;
} item;

int readitem(FILE *fp, item *itm)
{
    char buf[MAXLINE];

    if (fgets(buf, MAXLINE, fp) == NULL)
        return 0;

    return sscanf(buf, "%lf%lf%lf", &itm->cost, &itm->qty, &itm->disc);
}

The readitem function would get the next record, and read it into the itm pointer. You can call the function in a loop to get all the items:

#define MAXITEMS    255

item arr[MAXITEMS];
size_t i;
FILE *fin;

for (i = 0; i < MAXITEMS && readitem(fin, arr + i); ++i)
    ;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot... i really have a lot to learn when it comes to C programming... it is old and difficult yet challenging...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.