K&R2 - Piece of code not working.

This is a discussion on K&R2 - Piece of code not working. within the C Programming forums, part of the General Programming Boards category; Hello everyone, this is my first post here so I salute you all! I am learning C after "The C ...

  1. #1
    Registered User
    Join Date
    Nov 2009
    Posts
    1

    K&R2 - Piece of code not working.

    Hello everyone, this is my first post here so I salute you all!
    I am learning C after "The C programming language-second edition" by Dennis Ritchie. There is a piece of cod that doesn't do what it should: counting characters.

    Code:
    #include <stdio.h>
    
    main ()
    
    {
    long nc;
    
    nc = 0;
    while (getchar() != EOF)
          ++nc;
          printf("%ld\n", nc);
    
    
    }
    I am using windows7 , devc++ and I am running exe files in cmd. When I run the code above, I can input characters but after hitting Enter I don't get any number( to show how many characters I typed ). I do not have any previous experience with programming languages so please explain at a noob level!
    Thank you!

  2. #2
    Registered User
    Join Date
    Feb 2009
    Posts
    35
    here is the key line

    Code:
    while (getchar() != EOF)
    what this means is the while loop (which just increments the counter by one) will continue as long as you do not enter the EOF character.

    another thing to note is this character: \n

    that is the newline character. whenever you press enter, you are entering the newline character. now as the program itself is counting characters, it will count \n as a character. this is why pressing enter appears to do nothing. the program is still waiting for you to enter the next character

    to end the while loop you need to enter the EOF character. you are on windows so I think you press ctrl + z. you should see ^Z come up. press enter and the while loop will terminate and print the number of characters that you have entered

  3. #3
    Registered User redruby147's Avatar
    Join Date
    Sep 2008
    Location
    England
    Posts
    37
    It should work if you run it at command line (wherever that is on windows 7) and give it a text file. For example:

    Code:
    $ ./loop.o < oof.txt 
    8

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 05-14-2009, 04:13 PM
  2. Replies: 3
    Last Post: 05-09-2009, 08:37 PM
  3. Replies: 8
    Last Post: 01-18-2008, 03:06 AM
  4. Obfuscated Code Contest
    By Stack Overflow in forum Contests Board
    Replies: 51
    Last Post: 01-21-2005, 03:17 PM
  5. Help with a little piece of code
    By cdonlan in forum C Programming
    Replies: 5
    Last Post: 11-15-2004, 11:38 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21