-
gets(); problems
I am a fairly new C programmer and am having trouble using
gets().
I am using it to get values for structure members from keyboard input (not sure if this is important or not) The actual problem is that when executing, the first gets() statement is ignored, unless I put two statements together.
For example:
printf("Enter Make and Model: ");
gets(car[rec_num].make_model);
Becomes
printf("Enter Make and Model: ");
gets(car[rec_num].make_model);
gets(car[rec_num].make_model);
Can anyone shed any light as to why this is happening.
I am using Borland C++ Builder to compile my programs (Again not sure if that important but hey...)
-
First, don't use gets. There's a safer version of gets called fgets, second, the problem is probably caused by a scanf earlier in the program. It reads some input but leaves a newline character in the input stream and gets will read just the newline, causing you to need two calls to gets. Try this:
printf("Enter Make and Model: ");
while ( getchar() != '\n' );
fgets(car[rec_num].make_model, sizeof car[rec_num].make_model, stdin );
-Prelude
-
Hi!
I had the same problem. Donīt use scanf() and gets() if possible!
klausi
-
is it possible to use fgets on ex.a buffer
if:
char buffer[30]; /* here we have some data, text */
fgets(car[rec_num],sizeof car[rec_num]. buffer);
Mx.
-
>is it possible to use fgets on ex.a buffer
No, fgets will only read from a FILE *. To read data from a string use sscanf, for example:
sscanf ( buffer, "%s", car[rec_num].data );
The conversion flags are the same as scanf, and you have to be just as careful not to overflow the variables you are reading to.
-Prelude