Search code examples
cfilestructfgetsscanf

sscanf statement stops the program


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


struct urunler {
    int kod;
    char Ad[16];
    int stok;
    float fiyat;
};

void urunTara(struct urunler* inputs,int *amount);

int main()
{
    struct urunler Urun[50];
    int amount = 0;



    urunTara(Urun,&amount);
}

void urunTara(struct urunler *inputs,int *amount){
    char Temp[150];
    FILE *fPtr;
    fPtr = fopen("urunler.txt","r");
    if(fPtr == NULL){
        printf("File not found!");
    } else {
        while(!feof(fPtr)){
            fgets(Temp,100,fPtr);
            sscanf(Temp,"%d %s %d %f",&(inputs[*amount].kod),inputs[*amount].Ad,&(inputs[*amount].stok),&(inputs[*amount].fiyat));
            *amount++;
        }
    }

};

I am relatively new to C, and just started learning about structs. The text file contains these:

25 televizyon 1000 150.25
40 video 500 25.45
50 plazma 75 2300.50
76 dvd 20000 90.00
85 supurge 700 110.75
90 buzluk 250 10.00
95 teyp 1250 8.99 

The problem i have here is with the sscanf. When i do all these inside the main function, it works great. However when i try to do it in the function urunTara something goes wrong with the sscanf statement and the program stops working. I successfully passed values to &(inputs[*amount].kod) and other adresses by using scanf. But can't understand what's the problem with this sscanf statement.


Solution

  • *amount++;
    

    is similar to

    *(amount++);
    

    which means dereference amount and then increment amount to the element after that.
    Which is not correct.

    Change *amount++; to (*amount)++;, which will increment the dereferenced value.

    Refer this and this for more details