Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

K&R C Counting Characters

Tags:

c

linux

I'm working out of the K&R book, and I'm on the code example of how to count characters from a stream of text. I copied their code and tried running it, but when the command line prompts you for characters, the loop doesn't exit and thus will never print out the character count. Is there an error here I'm not catching?

#include <stdio.h>

main() 
{
     long nc;
     nc = 0;
     while(getchar() != EOF) {
          ++nc;
     }
     printf("%1d\n", nc);
}
like image 576
Andrew Avatar asked Jan 23 '26 22:01

Andrew


2 Answers

Whenever you want to stop it just send the EOF signal to the shell.

Ctrl+d in Linux or Ctrl+z on Windows.

By the way (as additional info) Ctrl+c send SIGINT to a process in Linux and on Windows it does something similar.

like image 108
Paulo Bu Avatar answered Jan 25 '26 10:01

Paulo Bu


Have you tried to press Ctrl+D (on Linux) or Ctrl+Z (on Windows)? If yes then It will come out of loop for sure. On pressing these keys, it will return EOF and loop will terminate.

like image 22
haccks Avatar answered Jan 25 '26 12:01

haccks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!