count char prog from K&R

Started by ly47, June 18, 2014, 11:45:19 AM

Previous topic - Next topic

ly47

Hi
I'm refreshing my c knowledge from K&R book (The C (ANCI) Programming Language)
There are some inOut progs that use EOF,but I can't terminate the console, and see result.
When compiling with GCC (Cygwin) it works fine.
Attached file.
Thanks
ly

neo313

#1
Technically getchar returns an int not long, but that is not the problem.

To get EOF you usually enter: on windows control+z and on linux control+d.

ly47

Hi neo313
Thanks a lot.
Now I can see ...
ly

frankie

As already said use <Ctrl>+'Z' to generate EOF in windows, but to get accurate count of characters before ^Z unbuffer the standard input:

#include <stdio.h>

int main(void)
{
long nc;

nc = 0;
setvbuf(stdin, NULL, _IONBF, 0);
while (getchar() != EOF)
++nc;
printf("%d\n", nc);

return 0;
}


The long holds the count not the input.
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide

czerny

Quote from: frankie on June 18, 2014, 01:27:20 PM

setvbuf(stdin, NULL, _IONBF, 0);

Although _IONBF means unbuffered, there is a ENTER necessary after the ^Z. That is strange! That looks like a linebuffer!
And, if setvbuf() is not used, the first ^Z is eaten. That could not be a buffer problem.

czerny

frankie

Quote from: czerny on June 18, 2014, 02:50:05 PM
Quote from: frankie on June 18, 2014, 01:27:20 PM

setvbuf(stdin, NULL, _IONBF, 0);

Although _IONBF means unbuffered, there is a ENTER necessary after the ^Z. That is strange! That looks like a linebuffer!
And, if setvbuf() is not used, the first ^Z is eaten. That could not be a buffer problem.

czerny
Yes,
this almost normal in MS inputs  >:(
I don't take any more care, I spent a lot of time for these bulls....  >:(
When working with MS stdin, stdout and stderr let him have an ENTER and don't care  ;D
A different solution is to use _getche() and compare for 0x1A (^Z) instead of EOF...
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide