简体   繁体   中英

Using fscanf() to read from a csv file in C

I'm having a bit of trouble with this piece of code. I have a file products.csv that I'm trying to read values in from and store in a struct. One of the lines are

Book,B123,The Hunt for Red October,12.99,28

Because the title has whitespaces in it, I know I need to use [^,] instead of %s so fscanf() doesn't stop at whitespaces, but it's messing up the reading of the file and I don't know exactly how to fix it. Here's the code:

typedef struct {
    char productType[15];
    char productID[4];
    char productDescription[100];
    double productPrice;
    int quantityInStock;
} product_t;    

int main() {
    product_t product1;

    read_products(&product1);
}

int read_products(product_t *product) {
    FILE *inFile = fopen("products.csv", "r");

    fscanf(inFile, "%[^,] %[^,] %[^,] %lf %d", product->productType, product->productID, product->productDescription, product->productPrice, product->quantityInStock);

    printf("%s %s %s %lf %d", product->productType, product->productID, product->productDescription, product->productPrice, product->quantityInStock);
}

You are forcing a space after the comma and you are not parsing the comma. Change this

"%[^,] %[^,] %[^,] %lf %d"

into this:

"%[^,],%[^,],%[^,],%lf,%d"

Other that that you have more errors:

  • productID[4] you need an array of 5 chars to accomodate for the \\0 terminator.

  • productPrice and quantityInStock are not pointers, so in the scanf you need to pass their pointer ( &product->productPrice , &product-> quantityInStock )

Check a working example here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM