2

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?

4
  • 1
    You asked a similar question an hour ago. Commented Oct 6, 2018 at 21:13
  • 1
    You could try 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 %s and %d ignore leading whitespace. Commented Oct 6, 2018 at 21:15
  • & you should have edited it instead asking a new one to the same topic. Commented Oct 6, 2018 at 21:15
  • 1
    @WeatherVane %s eats delimiter too so he should better use [^,]. Commented Oct 6, 2018 at 21:43

1 Answer 1

4

my output is 'bananas,5,0'. It seems like it is doing the first part correctly but then adding another ,0.

Because %s eats your delimiter(,) too, hence putting complete bananas,5 into fruit variable.

If you had checked the return value from fscanf it was just returning 1 and it was not reading %d into price variable.

Solution:

You could just use [^,] to read the string using , as delimiter and put fscanf in while loop checking return value for 2.

Sample code.

FILE * fptr = fopen("fruit.txt", "r");
char fruit[10];
int price = 0;

while(fscanf(fptr, "%9[^,],%d%*[\n]", fruit, &price) == 2)
    printf("%s,%d\n", fruit, price);

fclose(fptr);
Sign up to request clarification or add additional context in comments.

5 Comments

@User9123 %9 means fscanf should only read max of 9 char. That is done to avoid buffer overflow since you have declared fruit[10]
@User9123 and %* means read the input but do not assign it to any arguments in fscanf. That is done to eat up the input until reaching end of the line.
@Swordfish my comment got removed I don't know how.
@kiranBiradar I'm innocent.
@Swordfish yes you are! Some moderator must have removed it.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.