L
Luke Wu
I have been using the getline function from K&R2 for simple character
input.
The prototype is
int getline(char *s, int limit); /* returns 0 to signal EOF */
This function simply calls getchar() in a loop, which breaks if EOF or
too much input occurs (and places necessary '\0').
I always made sure the buffer pointed to by s was large (corresponding
to large limit argument). I only did this thinking that if the user
typed in a lot, then those characters that were not taken in (because
the limit has been reached), then those characters will be sitting in
my input stream waiting to attack the next naive character input.
Today I tested this fear, and it wasn't true. The remaining characters
disappeared when I typed in a lot of junk...
..#include <stdio.h>
..#define MAXLINE 4
..int getline(char line[], int max);
..int main()
..{
.. int length;
.. char line[MAXLINE];
..
.. while((length = getline(line,MAXLINE)) > 0)
.. {
.. puts(line);
.. }
..
.. system("PAUSE");
..
.. return 0;
..}
Sample input/output (my console):
input echo: 12345678
output: 123
input echo: 12345678
output: 123
What I was expecting (which always made me set MAXLINE very high):
input echo: 12345678
output: 123
input echo: 12345678
output: 456
(with 7812345678 still waiting to be read thereafter).
Is there something I am getting wrong? Can I get over my fear and set
MAXLINE to a reasonable value from now on? (Already read the FAQ)
Advanced Thx
input.
The prototype is
int getline(char *s, int limit); /* returns 0 to signal EOF */
This function simply calls getchar() in a loop, which breaks if EOF or
too much input occurs (and places necessary '\0').
I always made sure the buffer pointed to by s was large (corresponding
to large limit argument). I only did this thinking that if the user
typed in a lot, then those characters that were not taken in (because
the limit has been reached), then those characters will be sitting in
my input stream waiting to attack the next naive character input.
Today I tested this fear, and it wasn't true. The remaining characters
disappeared when I typed in a lot of junk...
..#include <stdio.h>
..#define MAXLINE 4
..int getline(char line[], int max);
..int main()
..{
.. int length;
.. char line[MAXLINE];
..
.. while((length = getline(line,MAXLINE)) > 0)
.. {
.. puts(line);
.. }
..
.. system("PAUSE");
..
.. return 0;
..}
Sample input/output (my console):
input echo: 12345678
output: 123
input echo: 12345678
output: 123
What I was expecting (which always made me set MAXLINE very high):
input echo: 12345678
output: 123
input echo: 12345678
output: 456
(with 7812345678 still waiting to be read thereafter).
Is there something I am getting wrong? Can I get over my fear and set
MAXLINE to a reasonable value from now on? (Already read the FAQ)
Advanced Thx