0

I'm writing a program that parses a csv file with the following format:

hotdog,10,2,1.5

bun,10,2,0.5

The code should strip each line of the file, and as of right now I'm just trying to print the values to make sure the format is correct. My problem is with correctly interpreting the number data - instead of printing the integer values in the csv file, the program is printing zeroes. The program properly parses the first field of each record in the csv, so I think the problem has to do with my formatting of atoi. Here's the code I've written:

char buffer[512]; //512 byte buffer holds the 10 food item names
char* currentLine = buffer; //a temporary pointer to hold the current line read from the csv file

FILE* fp = fopen("inventory.csv", "rw"); //open the inventory.csv file with read and write capabilities.
int i = 0; //counter
while(fgets(currentLine, 1024, fp) != NULL){
    printf("%s\n", strtok(currentLine, ",")); //get first field. Should be the food name.
    printf("%d\t", atoi(strtok(currentLine, ","))); //get second field. Should be stock amount
    printf("%d\t", atoi(strtok(currentLine, ","))); //get third field.
    printf("%f\n", atof(strtok(currentLine, ","))); //get forth field.
    i++;
}
fclose(fp);

Running that as is produces the following output:

hotdog
0   0   0.000000
bun
0   0   0.000000

Is the issue with my formatting of atoi?

1
  • 2
    how do those 512 and 1024 correspond?
    – mnagel
    Mar 9, 2014 at 20:51

2 Answers 2

2

Have a look at the documentation for strtok, e.g.: http://www.cplusplus.com/reference/cstring/strtok/

Only the first call expects the buffer. Subsequent calls should pass a null-pointer to retrieve the following token.

0

The issue is with strtok. After your first call of strtok, if you want it to continue parsing the same string rather than starting at the beginning, you have to provide NULL as the first parameter. See documentation: http://www.cplusplus.com/reference/cstring/strtok/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.