0

The code is:

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

        int main (void)
        {
            char ch,str[100],sen[100];
            printf("enter the string : ");
            fgets(str,sizeof(str),stdin);
            printf("enter the character : ");
            scanf("%c",&ch);
            printf("enter  the sentence : ");
            fgets(sen,sizeof(sen),stdin);
            printf("character is : %c\n",ch);
            printf("string is : %s\n",str);
            printf("sentence is : %s",sen);
            return 0;
        }

this is how i expect my programm to work: input:

    enter the string : abcde
    enter the character : k
    enter the sentence : i am a beginner.

output:

    character is : k
    string is : abcde
    sentence is : i am a beginner.

this is what it results in :

    enter the string : abcde
    enter the character : k
    enter  the sentence : character is : k
    string is : abcde
    
    sentence is :

This program is not prompting the user to input sentence. Please tell me why this fgets() function is not working properly.

  • `fgets()` is only for reading things. Therefore it won't prompt things. – MikeCAT Nov 19 '20 at 14:10
  • 1
    `scanf("%c",&ch);` reads only one character. It leaves newline character in the buffer if it is entered and the newline character will consumed by following `fgets()`. – MikeCAT Nov 19 '20 at 14:14
  • Call getchar() after your scanf to consume the newline character left in the buffer. – alex01011 Nov 19 '20 at 15:36

1 Answers1

2

fgets is working just fine. You do not flush stdout, so the printf writes data to an internal buffer but does not produce any actual output before fgets blocks on a read. Just add fflush(stdout) after the printfs.

William Pursell
  • 204,365
  • 48
  • 270
  • 300