0
typedef struct {
    char product_id[10];
    double price;
    int yr,mm,dd,hr,min,sec;
    int flag;
} purchase_t;

void
read_purchases(purchase_t *purchase[], int *num_purchase){
    int c;

    while ((c=getchar()) != EOF){
        purchase_t *new = malloc(sizeof(purchase_t));
        scanf("%s", new->product_id);
        scanf("lf",&new->price);
  ***** scanf("%d:%d:%d:%d:%d:%d",&new->yr,&new->mm,&new->dd,&new->hr,&new->min,&new->sec); 
        scanf("%d",&new->flag);

        int i;
        for (i=strlen(new->product_id); i>=0; i--){
            new->product_id)[i+1] = new->product_id[i];
        }
        new->product_id[0] = c;

        purchase[*num_purchase] = new;
        *num_purchase += 1;
    }
}

Is there a simpler way you approach line ***** or should I stick with this approach? P.S The program does the required job

  • 1
    You might want to use `fgets` to read full lines, and then `sscanf` to parse them. That will also help solve the problem with the `getchar` call reading the first character of the `product_id`. – Some programmer dude May 30 '20 at 02:44
  • If it's working, then it's mostly fine. I disagree with @Someprogrammerdude in that the standard IO lib is already buffering the input once. Buffering it again doesn't add value that I can see. The exception would be if you'd like to count input lines for error messages or similar. The one weird bit of your code is reading a character to check for end of file. Saying `while (!feof(stdin)) {` should work fine. Then the crazy shifting of the first string value can be removed. – Gene May 30 '20 at 03:33
  • @Gene See [Why is `while(!feof(fp))` always wrong?](https://stackoverflow.com/questions/5431941). The correct way to deal with `EOF` is to check the return value of each `scanf`. Any one of them could reach the end-of-file, so every one of them needs to be checked. – user3386109 May 30 '20 at 04:14
  • 1
    @Gene Using `fgets` isn't about buffering, it's more about being able to handle invalid input. That together with checking what `sscanf` (if used) returns help detect fauly or invalid input much easier and also makes it much easier to handle. – Some programmer dude May 30 '20 at 07:51

0 Answers0