malcolm@55bank.freeserve.co.uk says...[color=blue]
> "Spartan815" <absolutspartan@hotmail.com> wrote in message[color=green]
> > is there another function or way of going about getting input from the
> > command line besides getch(). Right now, Im just doing a simple
> > while loop (terminated by a new line character) to get input, but I also
> > want to be able to save up to 10 entries so that a history can be
> > display. I know thats rather open-ended, so really my better
> > question is can anyone point me to some good C resources online so
> > I can actually read about it...[/color]
>
> getc() is the best function for reading from stdin. gets() is unsafe,
> scanf() is difficult to use, fgets() has subtle problems on overflow.[/color]
I'll second all that. But scanf has the additional problem of necessarily
parsing your input in ways that don't allow you to definitively recover the raw
input.
I have a webpage explaining all of this, with sample code, here:
http://www.pobox.com/~qed/userInput.html
[color=blue]
> So write this function
>
> char *getline(void)
>
> calls malloc() and getc() to return a line from stdin.
>
> Now all you need is an array of character points
>
> char *history[10];
> int current = 0; /* this is not strictly needed but may make things easier
> to understand */
>
> Intitialise all elements of history to NULL. Then for the first ten lines
> read in the lines, incrementing current. When current gets to ten, the array
> is full. Therefore free the top entry (history[0]) and call memmove() to
> move all the pointers up one place. Then add your newly read line to the
> bottom.[/color]
That's one way, but why not just retain current as a modulo 10 value rather
than shifting your whole history? For example, using the code I indicated on
the webpage above, we can write simply:
char * history[10] = {NULL, ..., NULL};
int current = 0;
while (...) {
free (history[current % 10U]); /* free(NULL) is ok */
getstralloc (&(history[current % 10U]));
current++;
...
/* Dump the history */
for (i=current-10; i < current; i++) {
if (history[i % 10U]) {
printf ("%d) %s\n", i, history[i % 10U]);
}
}
}
There are ways to dramatically reduce the cost of the "%" operations, but I
will leave that as an exercise to the reader.
--
Paul Hsieh
http://www.pobox.com/~qed/ http://bstring.sf.net/