#include <stdio.h>

int main() {

	char name[50];

	printf("enter your name:");
	gets(name);
	puts(name);
	return 0;
}

hello,
the above program should first print out "enter your name:", but it does not.

it occurs in this way on the console:
---------------------------
abc
enter your name:abc
---------------------------

it prints "enter your name" after I enter any input.
What can be the problem?

Edited 6 Years Ago by gangsta1903: n/a

I found the a solution in the tutorials section.

here a function to read a line :

char *mygetline(char *line, int size)
{
   if ( fgets(line, size, stdin) )
   {
      char *newline = strchr(line, '\n'); /* check for trailing '\n' */
      if ( newline )
      {
         *newline =  '\0'; /* overwrite the '\n' with a terminating null */
      }
   }
   return line;
}

However, I still dont know why it happens in this way.

Edited 6 Years Ago by gangsta1903: n/a

I think,

fflush(stdout);

solves the problem.

so, this also works:

#include <stdio.h>
#include <string.h>

int main(void)
{
   char name[50] = "";
   printf("enter your name: ");
   fflush(stdout);

   gets(name);
   puts(name);

   return 0;
}

About

gets(name);

This is what manpages has to says about gets()

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.

Edited 6 Years Ago by gerard4143: n/a

Comments
Damn straight!
This question has already been answered. Start a new discussion instead.