jinglei
jinglei

Reputation: 3353

c - Why pressing enter triggers getchar() to terminate?

As Enter is not EOF, getchat() should be able to recognize \n when I press Enter.

In C document:

Return Value The obtained character on success or EOF on failure.

However, when I run

#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[]) {
    int c, q = 1;
    while ((c = getchar()) != EOF) {
        if (c == '"') {
            printf("%s", q ? "``" : "''");
            q = !q;
        }else{
            printf("%c", c);
        }
    }
    return 0;
}

There showed the output but the program is not terminated and it is waiting for more input.

This is "quote"Enter

output:This is ``quote''

press Enter

I wonder whether the operating system matters because I'm under OS X10.10 and it is said that \r starts a new line rather than \n under OS X.

Also, I'm not sure whether the debugger matters because I used Xcode to run the program.

**Ctrl-D would terminate the program and show the output right after my Input.

But Enter would output the current stdin and then wait for new input.

I don't have any other ideas why this happened so far.

Upvotes: 1

Views: 607

Answers (1)

fluter
fluter

Reputation: 13786

Press enter does not terminate your program, it add a new line to the input stream, it won't add an EOF, depends on which shell you are in, you can use Ctrl-D to mark EOF of stdin and terminate your program.

The standard streams are line buffered, and the behavior of line buffered streams are defined by the standard as follows:

When a stream is line buffered , characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered. Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment.

Upvotes: 1

Related Questions