fscanf from txt file is reading the last record twice

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rutabuga
    New Member
    • Jun 2008
    • 1

    fscanf from txt file is reading the last record twice

    after opening the text file the the prog is soposed to read each record into certain variables and then display the variable name to the screen

    the problem i am geting is that the last record in the text file is being printed
    twice

    the txt file is formated as so
    4 Jennifer f n
    3 Alexandra f n


    while (!feof(fp))
    {
    fscanf(fp, "%d %s %c %c" , &age, &name, &sex, &sn);
    printf("the data in name is %s\n",name)
    }
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    Two hints. I want to see if you can figure this out for yourself.

    1) feof does not do what you think it does. Or put another way. How would you know you have reached the end of something?

    2) Are you familiar with return values? Functions can return something. What could returning a value be useful for? Do the C library functions return values?

    Comment

    • Visame
      New Member
      • Dec 2007
      • 7

      #3
      Code:
      while (!feof(fp))
      {
      fscanf(fp, "%d %s %c %c" , &age, &name, &sex, &sn);
      printf("the data in name is %s\n",name)
      }
      I believe the problem lies in function FEOF.
      You can try this:
      Code:
      if (fscanf(fp, "%d %s %c %c" , &age, &name, &sex, &sn)==4)
      printf("the data in name is %s\n",name);
      or
      Code:
      while (fscanf(fp, "%d %s %c %c" , &age, &name, &sex, &sn)==4)
      {
      printf("the data in name is %s\n",name)
      }

      Comment

      • moonavar
        New Member
        • Nov 2012
        • 1

        #4
        hello here is our solution
        change coding of fprintf use %wd format that is use width for each variable
        fprintf(fp, "%3d %15s %1c %1c" , &age, &name, &sex, &sn);
        and also make same change in fscanf also
        while (fscanf(fp, "%3d %15s %1c %1c" , &age, &name, &sex, &sn))
        {
        printf("the data in name is %s\n",name)
        }
        and you will get your desire output.
        so now Cheersssssssss. .........

        Comment

        Working...