Thread: Code problem in K&R tutrial

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    187

    Code problem in K&R tutrial

    Hey guys I just started c programming reading K&R atm but I dont understand this code it says it counts characters but it doesnt output anything its like a notepad thingy there 2 codes acctually whish I dont understand thanks .......
    Code:
    #include <stdio.h>
    /* count characters in input; 2nd version */
    int main(void)
    {
          double nc;
          for (nc=0; getchar() != EOF; ++nc);
          printf("%.0f\n", nc);
          return 0;
    }
    2nd code its while version
    Code:
    #include <stdio.h>
    /* count characters in input; 1st version */
    int main(void)
    {
          long nc;
          nc = 0;
          while (getchar() != EOF)
              ++nc;
          printf("%ld\n", nc);
          return 0;
    }

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    It won't display any output until you signal end of file. From the keyboard, you can do this in unix with control-d; I think it's control-z on dos systems. You'll probably want to do it on its own line; that is, right after hitting enter.

    I'm sure K&R explain this (I don't have my book handy so I can't check), but EOF is a macro that means "end of file", and getchar() returns it when it reaches the end of file. That'd be either the actual end of a file if you're feeding it a real file, or it's a signal like control-d from the keyboard. It will keep looping and counting until it sees end of file.

  3. #3
    Registered User
    Join Date
    Apr 2009
    Posts
    187
    so in my case it wont ever close right ? coz there is no end of file

  4. #4
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    What is "your case"? If you're typing at the keyboard, which I presume you are (that's how I interpreted "like a notepad thingy"), then my previous answer applies. If not, please explain carefully what you're doing.

  5. #5
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    Why is the first version counting with double? That seems like a mistake....

  6. #6
    Registered User
    Join Date
    Apr 2009
    Posts
    187
    yah i understand it now i didnt read your comment properly thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. learning c from old k&r code
    By cmay in forum C Programming
    Replies: 13
    Last Post: 06-10-2009, 03:56 AM
  2. Problem : Threads WILL NOT DIE!!
    By hanhao in forum C++ Programming
    Replies: 2
    Last Post: 04-16-2004, 01:37 PM
  3. Replies: 5
    Last Post: 12-03-2003, 05:47 PM
  4. Help with code for simple Y2K problem
    By Mule in forum C++ Programming
    Replies: 3
    Last Post: 03-06-2003, 12:53 AM