Search code examples
cgotogets

gets() function gets skipped from the second time onwards


I was playing with C and wrote this code:

   1 #include<stdio.h>
   2 #define ASK_PROMPT printf("\nDo you want to continue(Y/N):");
   3 main()
   4 {
   5    char main[20], i;
   6    start:
   7    printf("Please enter your string:\n");
   8    gets(main);
   9    printf("\nstring entered was:\n \n%s\n", main);
   10   ASK_PROMPT;
   11   scanf("%c",&i);
   12       
   13   if(i=='Y'||i=='y')
   14       goto start;
   15   getch();
   16   return;
   17 }

when I execute this code, the goto loop is not working correctly. On providing y or Y response to question asked from line 10, loop does work and line 7 is again executed/printed but line 8 was skipped(doesn't wait for the input to be provided).

  • Can anyone explain why it is happening?
  • How do I fix it?

Solution

  • Fix

    Change scanf("%c",&i); to scanf("%c%*c",&i);.

    Problem

    The \n after inputting i is what is causing gets() not to wait for input.

    Good practices

    • Stop using gets(), goto etc. Instead, you can use fgets(), scanf() etc. Never use deprecated functions.
    • Change char array name from main to something else, say m.

    Thanks @Coolguy for the comment on use of scanf.