getchar() 循环不会无故结束

getchar() loop doesn't end from no reason

我有这个代码片段:

char key[32];
for (int i = 0; i < 32; i++)
{
    key[i] = getchar();
}

这显然应该接受 32 个字符然后停止。

问题是它不会在 i = 32 处停止并一直持续到(出于某种未知原因)我按下回车键。

你能解释一下为什么会这样吗?

continues eternally until (from some unknown reason) I press enter.

是的,这是正常的。参见例如http://c-faq.com/osdep/cbreak.html:

Input to a computer program typically passes through several stages. At the lowest level, device-dependent routines within the operating system handle the details of interfacing with particular devices such as keyboards, serial lines, disk drives, etc. Above that, modern operating systems tend to have a device-independent I/O layer, unifying access to any file or device. Finally, a C program is usually insulated from the operating system's I/O facilities by the portable functions of the stdio library.

At some level, interactive keyboard input is usually collected and presented to the requesting program a line at a time. This gives the operating system a chance to support input line editing (backspace/delete/rubout, etc.) in a consistent way, without requiring that it be built into every program. Only when the user is satisfied and presses the RETURN key (or equivalent) is the line made available to the calling program. Even if the calling program appears to be reading input a character at a time (with getchar or the like), the first call blocks until the user has typed an entire line, at which point potentially many characters become available and many character requests (e.g. getchar calls) are satisfied in quick succession.