Thread: Really newbie question from C Programming Language by Kernighan

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    13

    Really newbie question from C Programming Language by Kernighan

    Hey guys. Just started learning to code, and loving it so far. However, I have hit a snag with the often recommended C Programming Language by Kernighan and Ritchie, so I thought I would ask here.

    In section 1.5.3, he gives a program for counting characters,
    Code:
    #include <stdio.h>
    
    main()
    {
    long nc;
    
    nc = 0;
    while (getchar() != EOF)
    ++nc;
    printf("%ld\n", nc);
    }
    which is supposed to count the characters and then display it, but the program never displays the number of characters when I compile it in codeblock 10.05. Moreover, I can get it to count it out if I put the printf inside the loop, but I always gets one more number than the actual number of characters I type in. I have the same problem with
    Code:
    #include <stdio.h>
    main()
    {
    double nc;
    
    for(nc = 0; getchar() != EOF; ++nc)
    ;
    printf("%.0f\n", nc);
    }
    so I was just hoping someone could help with this. Thanks a lot.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by deckoff8
    the program never displays the number of characters when I compile it in codeblock 10.05
    When you ran the program, did you trigger EOF with CTRL + D or CTRL + Z?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    13
    I did not and that solved it. Thanks a lot

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C Programming newbie language barrier problem
    By Dixi in forum C Programming
    Replies: 7
    Last Post: 10-31-2011, 09:38 AM
  2. Replies: 5
    Last Post: 09-19-2011, 03:06 AM
  3. Replies: 2
    Last Post: 09-08-2010, 05:25 PM
  4. Replies: 8
    Last Post: 07-30-2008, 05:37 AM
  5. Newbie question: Kernighan-Ritchie C book- problem
    By plutonas in forum C Programming
    Replies: 2
    Last Post: 06-29-2005, 12:50 PM