I wrote a simple echo program, which reads standard input character-by-character and then prints it to standard output character-by-character.

#include <stdio.h>

int main() {
    int c;

    while ((c = getchar()) != EOF) {
        putchar(c);
    }
    return 0;
}

I was expecting it to break out of the while loop and terminate when I key-in Ctrl-Z, but the program keeps running.

Sample run:

(Input) all yuor base are belong to usCtrl-Z
(Output) all yuor base are belong to us
continue waiting for input...

One (strange) thing I noticed is the program will terminate only when Ctrl-Z is entered all by itself.

(Input) oh naise
(Output) oh naise
(Input) Ctrl-Z
programing terminates...

Why does this happen? Why does the program not terminate when Ctrl-Z is with other characters? WHY IS THE WORLD COMING TO AN END?!

Anyway, I am using Command Prompt (if that matters), and thanks in advance for any help.

Recommended Answers

All 3 Replies

Ctrl z is not a C function. IOW, the interpretation of ctrl-z is system dependent, and is not necessarily EOF. For example, on unix, ctrl-d is used as EOF. On systems where ctrl-z is used, it still doesn't always get interpreted as eof, as you have seen

for microsoft OS, ctrl-z is only EOF when it is found at the beginning of the input stream. in this case EOF is a negative value (-1). when ctrl-z is found in the middle of an input stream after text, it is interpreted as a non-printable ascii character, just like any other escaped character. in this case:

ctrl-a = 0x01
ctrl-b = 0x02
...
ctrl-z = 0x1A

you can test it yourself by trying different combinations of text and control characters. remember the printf() is blocking and will buffer the standard input until a newline is entered, so you'll have to hit <enter> after any given amount of text.

#include <stdio.h>

int main() {
    int c;

    while (1)
    {
        putchar(c = getchar());
        printf(" %c = %#X\n",c,c);
    }
    return 0;
}
commented: leet h4x0r +0
commented: helpful. +9

Thanks, that answered my question.

Wait...
"remember the printf() is blocking and will buffer the standard input until a newline is entered"
Don't you mean getchar()?

no i meant the printf() that i added in my version of your code.

depending on environment, printf often blocks the output until a newline is received.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.