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...

Garf365
  • 3,619
  • 5
  • 29
  • 41
Kimba
  • 25
  • 1
  • 3
    [The `fscanf` function](http://en.cppreference.com/w/c/io/fscanf) doesn't work for you? What else have you tried? Please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask), and learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – Some programmer dude Aug 19 '16 at 12:03
  • Also look into strtok to split delimiters. – fpes Aug 19 '16 at 12:11
  • 1
    I would read line by line and then use `sscanf(linebuf, "%d%d%d", &price, &quantity, &discount);` to get the numbers. – Klas Lindbäck Aug 19 '16 at 12:12

1 Answers1

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)
    ;
lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
  • Thanks a lot... i really have a lot to learn when it comes to C programming... it is old and difficult yet challenging... – Kimba Aug 21 '16 at 05:56