0

I met a problem here which is i used fgets to read user inputs, my goal is compare the inputs with "quit" by using strcmp function. if it returns 0 i will print it can compare otherwise it can not, but the current problem is it prints things out even the input string wasn't quit.

Below is my code and the outputs i have got..

#include <stdio.h>
#include <unistd.h>


int main()
{

    char buffer[355];

    printf("start say something here...\n");

    fgets(buffer, 355, stdin);

    printf("u entered %s", buffer);

    if (!strcmp(buffer, "quit"));
    {
        printf("i can compare\n");
    }
}

Outputs 1

start say something here...
no
u entered no
i can compare

Outputs 2

start say something here...
quit
u entered quit
i can compare
HardCoder
  • 3
  • 1
  • 1
    `fgets()` reads **and includes** the `'\n'` generated by pressing **Enter** in the buffer it fills. Use `buffer[strcspn(buffer, "\n")] = 0;` to remove it before calling `strcmp()`. (which is why you don't have to include the `'\n'` in `"u entered %s"` when you print it ... like you do in `"i can compare\n"`...) – David C. Rankin Mar 03 '22 at 03:25
  • 1
    [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input) – Retired Ninja Mar 03 '22 at 03:30
  • Additional [Specific Example for You](https://paste.opensuse.org/68886958) with other points to consider. (link good for 30 days until Wed Mar 30 22:34:37 CDT 2022) – David C. Rankin Mar 03 '22 at 03:35

0 Answers0