Summary: Removing excess characters from input stream
Michael Scott
scott at ncifcrf.gov
Fri Mar 22 22:46:00 AEST 1991
Here's a quick solution to my question regarding blowing away excess
characters unneeded by a program.
I was insistent thinking that there would be a library call to flush stdin.
Well no one referred me to a library call that could do that job -- and I
could not find one.
This solution is from John Hascall. It's simple and it works!!
> void get_string(string,length,prompt)
> char *string; int length; char *prompt;
>
> {
> fprintf(stdout,prompt);
> if ((fgets(string,length,stdin)) == (char *)NULL)
> {
> string[0] = '\0';
> fprintf(stdout,"\n");
> clearerr(stdin);
> }
> else
#ifdef YOURS
> string[strlen(string) -1 ] = '\0'; /* blow away the <cr> */
> fflush(stdin);
#endif
#ifdef MINE
if (string[strlen(string) - 1] == '\n') {
/*
* got the newline, blow it away
*/
string[strlen(string) - 1] = '\0';
} else {
/*
* no newline, read 'till we find it
*/
do {} while (getc(stdin) != '\n');
}
#endif
> }
--
_____________________________________________________________________________
Name: Michael Scott
Title: Sr. Systems Manager
More information about the Comp.lang.c
mailing list