Gets() not working

Ace picture Ace · Oct 30, 2013 · Viewed 21.4k times · Source

Im trying to use gets() to get a string from the user but the program seems to be passing right over gets(). There is no pause for the user to give input. Why is gets() not doing anything?

char name[13];
printf("Profile name: ");
gets(name);
printf("\n%s", name);

Answer

thisisprateek picture thisisprateek · Mar 25, 2017

Call getchar() before you call gets() or fgets(). Since gets() or fgets() is getting skipped due to an already present '\n' from previous inputs in stdin, calling getchar() would lead to itself getting skipped instead of gets() or fgets() or any other similar function. But remember its more of a hack and not a standard solution (I think so), and also use of gets() is forbidden.

        printf("\nEnter a String: ");
        getchar();
        //fgets(inputString, 100, stdin);
        gets(inputString);
        printf("\n%s", inputString);