问题空间:
while ((len = _getline(line, MAXLEN)) > 0)
是如何将 i
放入 _getline(...)
递增但不打印结果,直到按下输入键
?
代码示例:
#include <stdio.h>
#include <string.h>
#define MAXLEN 1000
int _getline(char s[], int max)
{
int c, i, l;
for (i = 0, l = 0; (c = getchar()) != EOF && c != '\n'; ++i) {
printf("%d\n", i);
if (i < max - 1) {
s[l++] = c;
}
}
if (c == '\n' && l < max - 1)
s[l++] = c;
s[l] = '\0';
return l;
}
int main()
{
int len;
char line[MAXLEN];
while ((len = _getline(line, MAXLEN)) > 0)
;
return 0;
}
最佳答案
How is it ... (various stuff does not occur) but not print the result until enter key pressed?
来自 stdin
的典型输入是行缓冲。 @John Coleman
没有任何东西可供getchar()
使用,它一直等待,直到Enter或'\n'
被按下,或者缓冲区已满(可能是 4k 个字符),或者发生 EOF - 然后它会返回第一个字符。对 getchar()
的后续调用可能会使用缓冲的行输入快速返回。
缓冲行为取决于实现。它不是由 C 指定的。
关于自定义 getline() 实现 - for 在 while 循环内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40096929/