PDA

View Full Version : Character Counting - What's wrong?


Gtaylor
June 12th, 2005, 02:40 AM
include <stdio.h>

// Count characters in input; 1st version

main()
{
long nc;

nc = 0;

while (getchar() != EOF)
++nc;
printf("%1d\n", nc);
}

This program is supposed to count the number of characters from input until an EOF is reached. When I compile/run it, I recieve no output from it with the value of nc which means EOF isn't being reached. I thought each time I hit 'enter' when being prompted for input, an EOF is sent. Am I doing something wrong here or do I have to specify a special character to equal EOF?

LordHunter317
June 12th, 2005, 09:25 AM
Enter doesn't send end-of-file, it sends newline.

To send EOF on a console, use Ctrl-D.

Also, in the UTF-8 locale, then won't give an accurate count of number of characters.

Gtaylor
June 12th, 2005, 12:20 PM
Ahh, I was wondering what the character was :) Good deal, I tried a bunch of other key combos to no avail.

eric.proctor
June 13th, 2005, 06:02 PM
Ahh, I was wondering what the character was :) Good deal, I tried a bunch of other key combos to no avail.
Also of note, instead of referring to EOL, you can refer to an unnamed variable value char 12. ie. char termcount = 12; as that is equal to carriage return in ascii values, if I'm not mistaken. It's been a while since I've thought of this, but it comes in handy to have that ascii chart around.

thumper
June 14th, 2005, 04:35 AM
Also of note, instead of referring to EOL, you can refer to an unnamed variable value char 12. ie. char termcount = 12; as that is equal to carriage return in ascii values, if I'm not mistaken. It's been a while since I've thought of this, but it comes in handy to have that ascii chart around.
Normally I use '\n' rather than hard coding values.

char newline = '\n';

LordHunter317
June 14th, 2005, 08:56 AM
Normally I use '\n' rather than hard coding values.

char newline = '\n';
That's hardcoding the same value.

poster_nutbag
June 14th, 2005, 02:16 PM
That's hardcoding the same value.

No, they just happen to have the same byte value. Try the same thing with unicode and it'll be different.

thumper
June 15th, 2005, 05:55 AM
That's hardcoding the same value.
It is actually platform dependant as well.

'\n' is different on *nix / windows platforms.

jdong
June 15th, 2005, 05:40 PM
so, if I try:


./charcount < /dev/zero


Your program will consume all of the system's resources counting.... ;)