#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?

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.

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.

commented: Damn straight! +19
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.