As others have said, comparing with "exit"
is failing because fgets()
included the newline in the buffer. One of its guarantees is that the buffer will end with a newline, unless the entered line is too long for the buffer, in which case it does not end with a newline. fgets()
also guarantee that the buffer is nul terminated, so you don't need to zero 256 bytes but only let fgets()
use 255 to get that guarantee.
The easy answer of comparing to exactly "exit\n"
required that the user did not accidentally add whitespace before or after the word. That may not matter if you want to force the user to be careful with the exit command, but might be a source of user annoyance in general.
Using strncmp()
potentially allows "exited"
, "exit42"
, and more to match where you might not want them. That might work against you, especially if some valid commands are prefix strings of other valid commands.
In the general case, it is often a good idea to separate I/O, tokenization, parsing, and action into their own phases.