strcmp not working

juan picture juan · Jun 9, 2009 · Viewed 29.4k times · Source

I know this may be a totally newbie question (I haven't touched C in a long while), but can someone tell me why this isn't working?

printf("Enter command: ");
bzero(buffer,256);
fgets(buffer,255,stdin);

if (strcmp(buffer, "exit") == 0)
    return 0;

If I enter "exit" it doesn't enter the if, does it have to do with the length of "buffer"?

Any suggestions?

Answer

poundifdef picture poundifdef · Jun 9, 2009

You want to do this:

strcmp(buffer, "exit\n")

That is, when you enter your string and press "enter", the newline becomes a part of buffer.

Alternately, use strncmp(), which only compares n characters of the string