PDA

View Full Version : Newbie C Programming problem



pez
August 10th, 2006, 01:19 PM
Hi, I was wondering if someone could tell me why I am having problems with this code:


#include <stdio.h>
/* count characters in input; 1st version */
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}



gcc -o test test.c
./test

I inputted 'test' and hit enter but all that happens is do a carriage return and doesn't represent EOF.

I'm banging my head here!

jayemef
August 10th, 2006, 01:39 PM
I didn't test your code, but EOF is Ctrl+D, not Enter.

Hope that helps...

moma
August 10th, 2006, 01:43 PM
Already told by "jayemef".

^d (CNTR + D) represents EOF.
Note that it will also count all CRs (ENTER keys).

pez
August 10th, 2006, 01:45 PM
Yes, that did work. Thank you very much! I actually have to hit CTR+D twice for it to assert EOF - is this correct?

moma
August 11th, 2006, 05:02 PM
Output from getchar() is buffered, so you must enter [RETURN] before it outputs anything.
Double ^D has to do with that buffer.

Google for "getche + linux"

Or take a look at this code that sets STDIN in non-buffered mode.
http://www.vivaolinux.com.br/dicas/verDica.php?codigo=1663
Requires
#include <unistd.h>
#include <termios.h>