0

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

Azeem
  • 11,148
  • 4
  • 27
  • 40
Milk_QD
  • 125
  • 8

2 Answers2

4

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?

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • OMG I feel so stupid now. Haha. Thanks a lot. Guys, your carriage return is scaned with fgets() too – Milk_QD Nov 01 '17 at 06:33
2

From fgets documentation, it keeps the carriage return \n in the input:

Reads at most count - 1 characters from the given file stream and stores them in the character array pointed to by str. Reading stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character. If no errors occur, writes a null character at the position immediately after the last character written to str.

So,

"Hello\n"

becomes:

"\nelloH"

That's what you are getting!

Azeem
  • 11,148
  • 4
  • 27
  • 40