I have this code snippet:
char key[32];
for (int i = 0; i < 32; i++)
{
key[i] = getchar();
}
which obviously is supposed to take in 32
characters and then stop.
The problem is that it doesn't stop at i = 32
and continues eternally until (from some unknown reason) I press enter.
Can you please explain why does this happen?
continues eternally until (from some unknown reason) I press enter.
Yes, this is normal. See e.g. 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.