-2

In this mini version of my program I am asking for user input. When the input is 'quit' or 'exit' I want the program to exit the while loop. The strcmp function doesn't seem to be working as I expect. I've spent some time looking for answers but can't find the issue. Any ideas?

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

#define BUFFER_SIZE 100
int main() {
    char request[BUFFER_SIZE];
    while(strcmp(request, "quit") != 0 && strcmp(request, exit) != 0) {
        fgets(request, BUFFER_SIZE, stdin);
    }
    return 0;
}
  • 3
    There's a trailing `\n`. Also the first loop contains UB. – iBug Oct 04 '18 at 17:22
  • Note that `strcmp(request, exit)` is comparing the function pointer for the `exit()` function with `request` — this is not good. You probably meant `strcmp(request, "exit")`. Pay heed to compiler warnings — and fix them before asking questions on SO. Or ask about the warning if you don't understand it. – Jonathan Leffler Oct 04 '18 at 18:48

2 Answers2

1

fgets reads the trailing \n and stores it in the buffer, so you're always comparing quit to quit\n.

Also at the first time the while loop examines its condition, very bad things could happen because your request array is not initialized.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
iBug
  • 35,554
  • 7
  • 89
  • 134
1

When the fgets reads input, it also reads the newline at the end of the input and stores it if there is enough space for it. This means that if you enter "quit", then request will actually contain "quit\n".

Also, the first time through the loop, request doesn't contain anything, so you're reading uninitialized values.

The simplest thing to do in this case is to just add the newline to the string to check against, and to change your while loop to a do..while loop so the check is performed at the end:

do {
    fgets(request, BUFFER_SIZE, stdin);
} while(strcmp(request, "quit\n") != 0 && strcmp(request, "exit\n") != 0);

Also note that you were passing the function exit in the second call , not the string "exit".

dbush
  • 205,898
  • 23
  • 218
  • 273