1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

K&R Learning Issue

Discussion in 'C' started by TimHarrington, Sep 4, 2010.

  1. TimHarrington

    TimHarrington New Member

    Sep 4, 2010
    Likes Received:
    Trophy Points:
    Hello there,

    The following code appears in K&R (p.18) second edition;

        long nc;
        nc = 0;
        while (getchar() != EOF)
        printf("%ld\n", nc);
    On the various IDEs I have tried (on windows), the code doesn't work as intended, at least not afaik. It never displays the number of characters, because it never reaches "EOF". Note - I did change the main to return type int and then return 0 at the end on my own, in case anyone feels like pointing that out.

    Now, having read around on the internet I noticed on stackoverflow that someone had a similar problem and replacing EOF with '\n' "solves" this issue, we now treat a newline as the end of input, which makes sense.. For the next program in the book this solution is also sufficient, but when we reach 1.5.3 we start line counting - now we can't use '\n' as K&R use that to count the number of new lines are being created and it wouldn't work anyway - it would always return '1'.

    I have tried ^D as a way of sending an end of file command to the output window, as suggested elsewhere, but this hasn't worked. I guess(ed) this is the problem when learning from a very old book - but even after downloading Turbo C 2.01 (1989) I had the same issue, it wouldn't exit the while loop as there is never an 'EOF'.

    So my question is this - what is the best IDE/compiler to use when reading K&R? I really want to run every program to help in my understanding, but if I keep running into these issues I am going to waste a lot of time trying to get even basic programs running and I assume this isn't an error in the book?

    A short term solution to getting the line counting program up and running isn't really sufficient imo, I really just want to get going - have an IDE/compiler that will run every program in the book without issue...

    ...Do I need to install Linux or is it really a problem with the book?

    Any help would be appreciated, I have searched high and low and spent a good few hours playing around with different compilers/IDEs that have been recommended only to get frustrated and forced to start a thread asking for some guidance.
  2. go4expert

    go4expert Moderator

    Aug 3, 2004
    Likes Received:
    Trophy Points:
    I will go with GCC

Share This Page