c - getchar() 循环不会无故结束

标签 c string infinite-loop getchar

我有这段代码:

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

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

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

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

最佳答案

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.

关于c - getchar() 循环不会无故结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49573509/

相关文章:

在无限 for 循环 C 程序中使用 getchar() 后,无法使用 fflush(stdin) 清除标准输入

c - 添加两个短号码时

c - 如何使用 fscanf 将字符串放入数组?

c - strstr() 导致段错误

java - 将字节转换为字符串再转换为字节

javascript - 什么时候字符串不是字符串?当它没有 includes() 方法时?

c - 加号 (++) 运算符应用于结构时的行为是什么?

iphone - Objective C 中的多个字符串替换

for-loop - Lua - 在 for 循环中更改 'stop' 变量的值,它还会正常终止吗?

bash - Docker在X时间后杀死了一个容器中的无限进程