After wasting too much time searching why my program doesn't execute gets() after using scanf(), I found a solution which is to use fflush(stdin) after scanf() to enable gets() to get a string.
The problem is that fflush(stdin) doesn't do what is expected from it: The program continues skipping gets() and I can't write any phrase in the console to be read.
My code is the next one:
#include <string.h>
#include <stdio.h>
int main(){
char nombre[10];
char mensaje[80];
printf("Type your name:\n");
scanf("%s", nombre);
fflush(stdin);
printf("Now, type a message:\n");
gets(mensaje);
printf("3/%s:%s",nombre,mensaje);
return 0;
}
Try this instead:
scanf stops at whitespace when reading a part. gets reads until the first new line. So what happens is scanf leaves behind a newline in the buffer, which gets immediately sees and thinks it was given a blank line.
If you take your original code and enter "name message", two pieces all on one line, you can see this in action - gets will still immediately return, but it will see the second part.
The \n in the scanf thing tells it to go ahead and consume that too.
If flushing std doesn't work, then try reading in the extra characters and discarding, as suggested here.
This will work:
Two big, major issues:
DO NOT USE
fflush
ON INPUT STREAMS; the behavior offflush
on input streams is not defined. Just because it appears to work in this situation does not mean it is correct.NEVER NEVER NEVER NEVER NEVER NEVER NEVER use
gets
- it was deprecated in the C99 standard and has been removed completely from the C2011 standard. It will (not might, will) introduce a major point of failure in your code.It's never a good idea to follow a
scanf
call with agets
call, sincegets
won't skip over any leading newlines left in the input stream byscanf
. Usescanf
to read bothnombre
andmesaje
.It's a good idea to use an explicit length specifier in the
scanf
call for%s
and%[
, otherwise you introduce the same security hole thatgets
does.EDIT
D'oh. I'm an idiot. If you're trying to read a string containing spaces, you can't use the
%s
conversion specifier. Use the%[
conversion specifier instead:That will read up to the next 79 characters or the newline, whichever comes first, and leaves the newline in the input stream.
Try
gets(stdin);
instead of