K&R Learning Issue

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

  1. TimHarrington

    TimHarrington New Member

    Joined:
    Sep 4, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hello there,

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

    Code:
    main()
    {
        long nc;
    
        nc = 0;
        while (getchar() != EOF)
            ++nc;
        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

    Joined:
    Aug 3, 2004
    Messages:
    306
    Likes Received:
    9
    Trophy Points:
    0
    I will go with GCC
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice