Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcmp not working

Tags:

c

strcmp

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?

like image 942
juan Avatar asked Jun 09 '09 01:06

juan


People also ask

Does strcmp work in C?

strcmp() in C/C++This function takes two strings as arguments and compare these two strings lexicographically. Syntax: int strcmp(const char *leftStr, const char *rightStr ); In the above prototype, function srtcmp takes two strings as parameters and returns an integer value based on the comparison of strings.

How do I get my strcmp to return 0?

The return value from strcmp is 0 if the two strings are equal, less than 0 if str1 compares less than str2 , and greater than 0 if str1 compares greater than str2 . No other assumptions should be made about the value returned by strcmp .

What does strcmp return if failed?

strcmp returns -1 (less than 0), 0 (equal) or 1 (greather than 0).


1 Answers

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

like image 196
poundifdef Avatar answered Oct 19 '22 04:10

poundifdef