#gets fgets use
6 messages in this thread
Hello to all you Amiga faithful.
I have been trying to use gets or fgets (with keyboard as stdin) to try
and avoid scanf(). I haven't been able to make it work right.
If I use gets or fgets alone the function goes right past them as if
they aren't there. If I put them in a loop such as:
while (gets (buf) != (char*) NULL)
or while (fgets (buf, 80, stdin) != (char*) NULL)
the program stays in the loop after I hit return or even overshoot the 80
characters. How do I get the routine to end on the carriage return?
What I'm trying to do is use it to fill a comment string in a record
structure of a file.
To avoid long threads of wasted forum memory, please accept my thanks
now for your advice.
Henry
Henry,
I tried your first example, as follows:
#include <stdio.h>
int main(void)
{
char buf[81];
while (gets (buf) != (char*) NULL)
printf("%s\n",buf);
}
This works just fine for me. Your comment about it 'staying in the loop may be
because of a misunderstanding of the return value from gets(). You will only
get the NULL if EOF is reached before ANY characters are present in the
keyboard buffer. That is, if you type anything at all, it will be echoed,
including just typing a <RETURN>. The EOF key on the Amiga is a CTRL-\
(CONTROL-Backslash), and pressing that key before any other keys, after entry
to the gets(), will drop you out of the loop.
changing the program to:
gets(buf);
printf("%s\n",buf);
works as expected, echoing the input, then dropping out.
You didn't mention which compiler you are using, but the above examples I tried
on Lattice.
-larry
Larry,
Thanks for the help with gets(). It's working now. I noticed something
else that explained some of the trouble. For one of my inquiries I have to
use a scanf() and what happens is the gets() that follows is skipped. I
got around it by setting up a dummy gets as follows:
scanf("%d/%d/%d", &year, &month, &day);
gets(dummy);/* This one gets skipped by scanf white-space I imagine*/
gets(buf); /* This one works */
Could you tell me how I keep my program from crashing if I type past
the buffer limit? And if it's not too much trouble, how can I reset that
crazy scanf() so it doesn't interfere with following commands? Oh yes, I
use the Manx 3.6a compiler.
Thanks, Henry
Not sure how to get around the problem with scanf(), except to say "Don't use
it." One way to ensure that all characters are emptied from the buffer before
asking for characters is to just use a loop, like…
while(gets(buf));
gets(buf);
The while() will empty the buffer, and the second line will do the gets().
There is no way to prevent a crash if you use gets() and type beyond the buffer
length. You should either use fgets(), which specifies a length, or write your
own gets(), using getchar().
-larry
Ummmm, Larry,
while(gets(buff));
will read the remainder of the file.
oops! You are right. I was taken in by the statement "gets() copies from stdin
until a newline is reached".
-larry