-2

I am doing a C project related to my lesson. I need to read words from a file named file2.txt whose content:

file2.txt:

stephen elis elis
awkward
hello bye

stephen ayse
goodbye 
book picture pencil

I am using:

FILE *file = fopen("file2.txt" , "r");
char word[15];
while(!feof(file))
    {
        fscanf(file,"%s",word);
        printf("%s" , word);
        printf("\n");

    }

But when the words are printed the result is:

stephen
elis 
elis
awkward
hello
bye
stephen
ayse
goodbye
book
picture
pencil
pencil   --> printed second time

Thus , last word is printed twice and I do not understand why. Please help me about fixing this error because time is limited to complete this error! Thank you...

Begumm
  • 69
  • 1
  • 2
  • 11
  • 4
    **Never** with `feof`... (and *hundreds* of duplicates). – Kerrek SB Dec 01 '13 at 10:49
  • Thank you WhozCraig but still I am not sure and I did not exactly understand what will be the best solution to my problem and I am new to C. – Begumm Dec 01 '13 at 11:12

1 Answers1

0

you can check fscanf return value

FIX: sorry, it should be used like this:

if (EOF != fscanf(file,"%s",word))
  printf ("%s\n" , word);

EDIT: Or maybe better:

  if (0 < fscanf(file,"%s",word))
      printf ("%s\n" , word);

since EOF value is (-1)

SHR
  • 7,940
  • 9
  • 38
  • 57