0

here is a fragment of my program

     #include<stdio.h>
#include<conio.h>
int main(void)
{
    int c;
    while ((c = getch()) != EOF)
    {
        if (c == '\t')
        {
            putchar('\\');
            putchar('t');
        }
        else if (c == '\b')
        {
            putchar('\\');
            putchar('b');
        }
        else if (c == '\\')
        {
            putchar('\\');
            putchar('\\');
        }
        else if (c == '\r')
        {
            puts("\\n");
          //  putchar('\n');
        }
        else{
            putchar(c);
        }
    }
    return 0;
}

and I want to terminate my input when I input EOF, but when I input ^Z I only get this: enter image description here so how can I input ^Z to terminate my input?

ha9u63a7
  • 6,233
  • 16
  • 73
  • 108
zhenganyi
  • 169
  • 10
  • 1
    What's the type of `c`? It should be `int`. If it's `char`, then it can never be `EOF`. – Mike Seymour Nov 13 '14 at 08:20
  • @MikeSeymour The code doesn't matter and is redundant, the question is more about the CMD terminal than the program in question. It's actually better suited to SuperUser.com – sashoalm Nov 13 '14 at 08:21
  • The EOF you're testing for in the `while` condition is not an EOF *character*, it's an actual end of file... or closed input stream, etc. – Dmitri Nov 13 '14 at 08:22
  • 1
    Found something related (I guess (-;): http://stackoverflow.com/questions/7373386/eof-in-windows-command-prompt-doesnt-terminate-input-stream – Robert Nov 13 '14 at 08:22
  • 2
    You can try `ctrl+D` – Mohit Jain Nov 13 '14 at 08:22
  • 1
    @sashoalm: Unless the problem is that `c` is the wrong type, which is one possible cause of the described symptoms. – Mike Seymour Nov 13 '14 at 08:22
  • Also see https://stackoverflow.com/questions/16136400/how-to-send-eof-via-windows-terminal – sashoalm Nov 13 '14 at 08:25

1 Answers1

3

Your program works perfectly ... but getch does not do exactly what you expect.

getch (from conio.h) and getchar (from stdio.h) both get one character at a time, but not at same level. getchar is higher level, and so :

  • reads on stdin (can be redirected)
  • waits for a full buffer in line oriented mode
  • is interrupted by a Ctrl-C (more exactly Ctrl-C is seen as a SIG_INT signal)
  • translates special characters Ctrl-D on Unix-Linux Ctrl-Z on Windows as EOF

On the other hand, getch is low-level (and exists in Microsoft systems but is not standard C) :

  • directly reads on the keyboard
  • pass any character including Ctrl-C and Ctrl-Z as is
  • the only possible interruption is via Ctrl-Break
  • never returns EOF ( == -1)

All examples using getch works the same : you define what will be your end of input character and manually test it, there is no magical EOF.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252