Pelles C forum

C language => Beginner questions => Topic started by: ly47 on June 18, 2014, 11:45:19 AM

Title: count char prog from K&R
Post by: ly47 on June 18, 2014, 11:45:19 AM
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
Title: Re: count char prog from K&R
Post by: neo313 on June 18, 2014, 01:02:13 PM
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.
Title: Re: count char prog from K&R
Post by: ly47 on June 18, 2014, 01:26:11 PM
Hi neo313
Thanks a lot.
Now I can see ...
ly
Title: Re: count char prog from K&R
Post by: frankie on June 18, 2014, 01:27:20 PM
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.
Title: Re: count char prog from K&R
Post by: 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
Title: Re: count char prog from K&R
Post by: frankie on June 18, 2014, 03:36:14 PM
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...