0

Here is program to read character from the console and print them in a reverse order.

#include<stdio.h>
main()
{
int ch, count = 0;
char a[100];
printf("Enter Charachters\n");
ch = getchar();
while(ch != EOF && count<100)
{
  a[count] = ch;
  count = count+1;
  ch = getchar();
}
printf("\ncount = %d\n",count);
while (count>0)
{   
  count = count -1  ;
  putchar(a[count]);
}
}

My questinon is: When we give EOF character (ctrl+D) after typing in a few characters on the console, it does not exit out of the loop. It does not add to the count variable but also does not exit the loop. Only if the EOF character is the first character after a newline character, it is read properly and the loop is exited. For eg if the sample input is:

abcdef
abc
ctrl+D

Then the code works fine but if the input is:

abcdef ctrl+D

The loop is not exited. Tell me a way to accomplish this.
Thanks

  • `EOF` is **no** character! It is an `int` value which cannot even be confused with a valid character. `crtl-D` does not send a character, but closes `stdin`. – too honest for this site Aug 16 '15 at 14:50
  • Thanks for that information. So is there any way to accomplish what I have asked in the queston? – Abhay Gupta Aug 16 '15 at 14:55
  • That seems to be related to buffering in your terminal. You should set it to non-buffered mode. – too honest for this site Aug 16 '15 at 15:02
  • possible duplicate of [Why do I require multiple EOF (CTRL+Z) characters?](http://stackoverflow.com/questions/5655112/why-do-i-require-multiple-eof-ctrlz-characters) and [this](http://stackoverflow.com/questions/32031934/why-eof-is-not-working-in-the-same-way) – Spikatrix Aug 16 '15 at 15:39
  • Olaf: neither files nor other input streams are closed automatically when EOF is signalled. And the observed behaviour has nothing to do with buffering. – rici Aug 16 '15 at 19:42
  • Thanks everyone. All your comments and answers helped. But, this answer was the most helpful: http://stackoverflow.com/a/30690100/2501038 – Abhay Gupta Aug 23 '15 at 15:13

1 Answers1

-1

ctrl-D is actually EOT (End of Transmission). ctrl-Z is EOF (End of File). That isn't specific to unix it is ASCII. unix libraries choose to interpret EOT as a way to signal end of input on character I/O.

Grv
  • 273
  • 3
  • 14
  • This is almost completely incorrect. On unix, the ctrl-D keypress is interpreted by the terminal driver, not the library; the application never sees it. And it is the precise interpretation which leads to the idea that it signals EOF; it only does so when it is the first character entered on a line. ASCII did not have an EOF character; ctrl-Z (0x1A) was [substitute](https://en.wikipedia.org/wiki/Substitute_character). – rici Aug 16 '15 at 18:12