Search code examples
ccharprintfscanfgets

What's wrong with my code? why gets function is not working?


I have declared 3 variables. here ch for store one character and s for store a single word and sen for a sentence or multiple words! But, when i run the code it is not giving the opportunity to give an input for sen variable.

I have tried to figure out the problem. but I failed! What's wrong with my code. can anyone help me please...

Here is my code...

#include<stdio.h>
int main()
{
    char ch, s[20], sen[100];
    scanf("%c%s",&ch,&s);
    gets(sen);
    printf("%c\n%s\n%s", ch, s, sen);
    return 0;
}

Solution

  • You should not use gets function for buffer overflow. Use fgets() instead.

    fgets() takes 3 arguments. one is str >>> pointer to an initialized string in which characters are copied. it also returns str.

    another is int n >>> number of characters to copy.

    and finally, file stream or stdin >>> reading from standard input.

    Use

    #include<stdio.h>
    int main()
    {
        char ch;
        char* s[20], sen[100];
        scanf("%c%*c\n", &ch);
        scanf_s("%19s", s, 20);
        fgets(sen, 100, stdin);
        printf("%c\n%s\n%s", ch, s, sen);
        return 0;
    }
    

    You are missing &sen which is supposed to take the input.