NO

Author Topic: count char prog from K&R  (Read 3235 times)

ly47

  • Guest
count char prog from K&R
« 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

neo313

  • Guest
Re: count char prog from K&R
« Reply #1 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.
« Last Edit: June 18, 2014, 01:34:51 PM by neo313 »

ly47

  • Guest
Re: count char prog from K&R
« Reply #2 on: June 18, 2014, 01:26:11 PM »
Hi neo313
Thanks a lot.
Now I can see ...
ly

Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2097
Re: count char prog from K&R
« Reply #3 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:
Code: [Select]
#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

  • Guest
Re: count char prog from K&R
« Reply #4 on: June 18, 2014, 02:50:05 PM »
Code: [Select]
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

Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2097
Re: count char prog from K&R
« Reply #5 on: June 18, 2014, 03:36:14 PM »
Code: [Select]
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