I'm trying to put values from a file into variables. I have a fruits.txt file with the following data.
bananas,5
apples,3
kiwi,7
The comma separates the name of the fruit from the price. My goal is to put the name into a string called fruit and the price into an int called price, move the file pointer to the next line, then print it.
FILE * fptr = fopen("fruit.txt", "r");
char fruit[10];
int price = 0;
fscanf(fptr, "%s,%d\n", fruit, &price);
printf("%s,%d\n", fruit, price);
fclose(fptr);
Is what I have so far. However, my output is bananas,5,0. It seems like it is doing the first part correctly but then adding another ,0. Does anyone know how to fix this?
while(fscanf(fptr, "%9s,%d", fruit, &price) == 2)but please be more generous with the size of the string, and, restrict the input length. And there is no need to pick off the trailing newline: both%sand%dignore leading whitespace.%seats delimiter too so he should better use[^,].