Skipping gets()?

0 San De · July 9, 2015
So I was trying to demonstrate the difference between scanf and gets to a friend but the gets() statement wasn't getting executed(fail). Can you please point out the error?

#include
#include


int main()
{
    char fName[30],lName[30];
    printf("Hi there!Enter your first name.\n");
    scanf(" %s",fName);
    puts("Please enter your last name.");
    gets(lName);
    printf("So your name is %s %s?",fName,lName);
    return 0;
}

The output was like:
Hi there!Enter your first name.
blah
Please enter your last name.//didn't stop for my input
So your name is blah ?


Post a Reply

Replies

Oldest  Newest  Rating
+2 Jon Z. · July 9, 2015
you need to clear the input buffer, because the return ('\n') at the end of the first input is still there.

fflush(stdin);



#include


int main()
{
    char fName[30],lName[30];
    printf("Hi there! Enter your first name.\n");
    scanf(" %s",fName);
    fflush(stdin); //clear the buffer
    puts("Please enter your last name.");
    gets(lName);
    printf("So your name is %s %s?",fName,lName);
    return 0;
}
0 c student · July 10, 2015
fflush (stream);

is only defined for output streams, not input.  using stdin with fflush invokes undefined behaviour and shouldn't be used.
there is a simple fix for this.  you just need to suppress the input for the newline character like so

scanf("%s%*c",fName);    // %*c will suppress \n

also, gets() is a deprecated function and should be avoided at any cost

from gets man page:
Bugs
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

http://linux.die.net/man/3/gets
  • 1

C

107,323 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator