0

For some reason my program messes up in the first while loop but I really don't understand why. Yesterday I was using standard redirection input for stdin and I'm assuming opening a file is basically the same thing. Why is it not working now?

This is the text file I saved as '.csv' and which I'm opening:

hotdog, 10, 2, 1.50
bun, 10, 2, 0.50
burger, 100, 10, 2.00

#include <string.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i = 0, j = 0; char command[25], str[100]; int quantity[100], limit[100]; double cost[100]; char *item[100]; char *token, *ptr; FILE *fp = fopen("inventory.csv", "rw"); if(fp == NULL) { perror ("Error opening file"); } //testing to see if program gets until here, then tries to copy data from CSV to arrays while(fgets(str, 100, fp) != NULL) { token = strtok (str,","); ptr = strdup(token); item[i] = ptr; sscanf (token, "%s", item[i]); token = strtok (NULL,","); sscanf (token, "%d", &quantity[i]); token = strtok (NULL,","); sscanf (token, "%d", &limit[i]); token = strtok (NULL,"\n"); sscanf (token, "%lf", &cost[i]); i++; } printf("hey"); for(j=0;j<i;j++) { printf("%s, %d, %d, %lf\n", item[j], quantity[j], limit[j], cost[j]); } strcpy(command, argv[1]); if(strcmp(command,"list") == 0) { for(j=0;j<i;j++) { printf("%s, %d, %d, %lf\n", item[j], quantity[j], limit[j], cost[j]); } } else { printf("wtf hello"); } return 0; } 
5
  • 3
    You're pointing fgets at stdin, not at the file you've just opened. Commented Mar 10, 2014 at 11:44
  • even once changing 'stdin' to 'fp', it still doesnt work Commented Mar 10, 2014 at 11:49
  • item[i] pointed to part of str. Commented Mar 10, 2014 at 11:52
  • How am I meant to store in item[i] exactly? This doesn't work either : token = strtok (str,","); sscanf (token, "%s", item[i]); Commented Mar 10, 2014 at 12:00
  • i copied token to another pointer before assigning item to that and now it works Commented Mar 10, 2014 at 12:12

1 Answer 1

3

In the following statements for sscanf address of the entry should be given

sscanf (token, "%d", &quantity[i]);

sscanf (token, "%d", &limit[i]);

sscanf (token, "%lf", &cost[i]);

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that was my main mistake -_-

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.