Jump to content

[SOLVED] print # of characters in C


rubing

Recommended Posts

I am following along with exercises from a book (C Programming), and one of the examples doesn't seem to be working.  I believe it's supposed to print the number of characters you enter, but it doesn't do anything.  Is there something wrong with my code?

 

#include <stdio.h>
main()
{
  long nc;

  nc=0;

  while (getchar() != EOF) 
    ++nc;

  printf("%ld\n",nc);
}

Link to comment
Share on other sites

A book really had that as an example?  Weird.

 

 

 

#define EOF    (-1)

 

Is what stdio.h has for me, and I would assume it is the same with all versions of stdio.

 

 

That said, when comparing a character to an integer, it compares the numeric equivalent of the character (for example, if the encoding is ASCII, 'a' == 97).  No character encoding that I know of uses -1, so entering that wouldn't exactly be possible.

 

 

Perhaps you could change the code to check for a line break or a period?

 

 

while(getchar() != '.') for example....

 

 

(Single quotes are used because double quotes would make it a null terminated char array.  In other words, it would be \2E\00 instead of \2E (hex representation), and of course a single character (as returned from getchar()) will never match a null terminated char array.)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.