Thread: No return on char counting program

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    31

    Question No return on char counting program

    When I execute the following piece of code I'm prompted to typed in some characters, however nothing happens when I press return. Surely a value should be returned indicating how many characters are contained in the input?

    Code:
    #include <stdio.h>
    
    main()
    {
    long nc;
    nc = 0;
    while(getchar() != EOF)
    ++nc;
    printf("%ld\n", nc);
    }

  2. #2
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    Ugh, formatting...

    Code:
    #include <stdio.h>
    
    main()
    {
       long nc;
       nc = 0;
       while(getchar() != EOF)
          ++nc;
       printf("%ld\n", nc);
    }
    Thats a little better and isn't the code clearer now too?
    As for your question here is a hint: EOF != '\n' (or maybe '\r' depending on platform)
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Because pressing return does not indicate EOF.

    Try using:
    Code:
    while(getchar() != '\n')
    instead.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Feb 2010
    Posts
    31
    Thanks all. One more thing..... when the program is running, how do I escape back to normal terminal node?

  5. #5
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    Well, once you escape your while() loop with either CTRL-D (EOF) or ENTER ('\n') it should print the number of characters and exit for you...
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 11-01-2009, 09:54 AM
  2. How can I make this code more elegant?
    By ejohns85 in forum C++ Programming
    Replies: 3
    Last Post: 04-02-2009, 08:55 AM
  3. New string functions
    By Elysia in forum C Programming
    Replies: 11
    Last Post: 03-28-2009, 05:03 AM
  4. OpenGL Window
    By Morgul in forum Game Programming
    Replies: 1
    Last Post: 05-15-2005, 12:34 PM
  5. fopen();
    By GanglyLamb in forum C Programming
    Replies: 8
    Last Post: 11-03-2002, 12:39 PM