Search code examples
cfgets

Please explain this behavior of fgets() in C


To my understanding, fgets() will scan for input until a carriage return(\n), but my this code shows otherwise. I do not know where the extra line come from. Can someone explain?

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

#define BUF_SZ 256

void reverse(char str[]) {
    /* fill in the function body please */
    for (int i = 0, j = strlen(str) - 1; i < strlen(str) / 2; i++, j--)
    {
        char temp; // perform the swap
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
}

int main() {
    char mesg[BUF_SZ];
    printf("Enter a message please=> ");
    fgets(mesg,BUF_SZ,stdin);
    reverse(mesg);
    printf("%s\n",mesg);
    return 0;
}

This is the output: enter image description here


Solution

  • You got an input of "Hello" followed by a newline. You reversed it, to get a newline followed by "Hello". Then you printed that out, followed by a newline.

    fgets(mesg,BUF_SZ,stdin);
    

    Okay, so now we have "Hello" followed by a newline.

    reverse(mesg);
    

    Okay, so now we have a newline followed by "olleH".

    printf("%s\n",mesg);
    

    And we output that, followed by another newline.

    What's the mystery?