Reputation: 419
Problem space:
How is it that while ((len = _getline(line, MAXLEN)) > 0)
would make the i
inside _getline(...)
increment but not print the result until enter key
pressed?
Code Example:
#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;
}
Upvotes: 0
Views: 283
Reputation: 154280
How is it ... (various stuff does not occur) but not print the result until enter key pressed?
Typical input from stdin
is line buffered. @John Coleman
Nothing is available to getchar()
, it waits and waits, until the Enter or '\n'
is pressed, or the buffer fills (maybe 4k characters), or EOF occurs - then it returns with the first character. Subsequent calls to getchar()
may return quickly using the buffered line input.
The buffering behavior is dependent on the implementation. It is not specified by C.
Upvotes: 1