Problem with fgets reading last line over and over

Discussion in 'C++' started by Trond Valen, Dec 6, 2005.

  1. Trond Valen

    Trond Valen Guest

    Hi!

    Anyone who knows what the reason might be? fgets is supposed to return
    null when reading EOF. I have a test for this, so my while loop should
    exit, but it doesn't ...

    Trond
     
    Trond Valen, Dec 6, 2005
    #1
    1. Advertisements

  2. Rule #1: Post Code
     
    Karl Heinz Buchegger, Dec 6, 2005
    #2
    1. Advertisements

  3. You forgot to post any code illustrating the observed behavior, so it
    is very difficult to know what the reason might be.

    The following should work:

    #include <stdio.h>

    int main()
    {
    char buf[42];
    char* ptr;

    while ((ptr = fgets(buf, sizeof buf, stdin)) != NULL) {
    /* do something with buf here */
    }
    return 0;
    }

    /Niklas Norrthon
     
    Niklas Norrthon, Dec 6, 2005
    #3
  4. Trond Valen

    mlimber Guest

    Rule #2: Prefer iostreams to C-style file streams:

    http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.1

    Cheers! --M
     
    mlimber, Dec 6, 2005
    #4
  5. Trond Valen

    deane_gavin Guest

    Rule #3: Make sure you test eof correctly with your C++ streams

    http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5

    Gavin Deane
     
    deane_gavin, Dec 6, 2005
    #5
  6. Rule #4: If you for some reason use C style I/O, make sure you test
    eof correctly with your FILE objects.

    /Niklas Norrthon
     
    Niklas Norrthon, Dec 7, 2005
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.