Jump to content

fscanf returns incorrect values in C

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
Guest_CheapFungus_*

Guest_CheapFungus_*
  • Guests
Hi! I've been having problems regarding my file reading. I've noticed that it returns a weird value, (it returns a 0.00) and stores this incorrect value in the structure.I've noticed that this happens usually if the file is empty. Here's the part of my code that deals with the reading of the file. I've initialized the fp in another part of the program, by the way.
I'd aprreciate all your help :)
int reads ()
{
    
    int i= 0, j;
    char c;
    
    fp = fopen("dishes.txt", "r");  
    
    
    
    if (fp != NULL)
    {
       while (!feof(fp))
       {
          fscanf (fp,"%50s %50s %f", dish[i].name, dish[i].describe, &dish[i].price);
          dishtotal++;          
          i++;
       }//while loop
       
    }//if
   // printf ("%d", i);
    
    fclose(fp);
    getch();
    return;
}  



The format of the file looks like this:


string1 string2 price(in float)
sundae chocolate 5.00
lasagna italian 50.00

and so on...

Edited by ZekeDragon, 21 March 2010 - 12:39 AM.
Please use [code] tags (the # button) when posting code.


#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Could you give us an example file that you open which causes the problem? You said it usually happens when the file is empty... which really shouldn't be that surprising. :P
Wow I changed my sig!

#3
Guest_CheapFungus_*

Guest_CheapFungus_*
  • Guests
Say I have a file that contains these:

Lasagna Italian Dish 10.00
Sundae Chocolate 9.00
Nachos Mexican 5.00


My program has a delete function which deletes the items in the file, so there are really instances that the file must be empty. I don't want it to return weird values because it kinda mucks up the program , so there :)

#4
Guest

Guest

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,414 posts
Maybe this will work:
if (dish[i].price==0) {
    printf("File is empty!\n");
    fclose(fp);
    return 1;
}
If it returns the weird value, say the file is empty and stop the program.
Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)

#5
farajnew

farajnew

    Newbie

  • Members
  • Pip
  • 2 posts

CheapFungus said:

fscanf (fp,"%50s %50s %f", dish[i].name, dish[i].describe, &dish[i].price);

} [/code]



.

Maybe the problem could be with using %50s
try without the "50" , since the largest string in English is 22 char and u r using 50 char to get string
:)
regards
FK

#6
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts
Avoid loop control using EOF. Instead, check the return value of fscanf for correctness.