Strcmp()
Sep 24, 2011 at 7:58am Sep 24, 2011 at 7:58am UTC
Hi everyone,
Can anyone tell me what is wrong with the following use of strcmp(), i know that it is supposed to return 0 if the comparison if the C-strings are equal, a Negative integer if first c-string is less than second c-string, or a positive integer if it is the other way. I always get a 1 with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <iostream>
using namespace std;
int main ()
{
char s1[] = "hello" ;
char s2[] = "hello" ;
strcmp (s1, s2) ;
cout<<"comparison: " <<strcmp;
return 0;
}
Last edited on Sep 24, 2011 at 7:58am Sep 24, 2011 at 7:58am UTC
Sep 24, 2011 at 8:05am Sep 24, 2011 at 8:05am UTC
1 2
strcmp (s1, s2) ;
cout<<"comparison: " <<strcmp;
So you carry out the strcmp function, but you don't actually store the result anywhere, and then you attempt to cout the function strcmp.
You should be storing the result of the strcmp function you're calling, and then outputting the result.
1 2
int x = strcmp (s1, s2) ;
cout<<"comparison: " << x;
Sep 24, 2011 at 8:07am Sep 24, 2011 at 8:07am UTC
Oh, Duh,
Thanks
Sep 24, 2011 at 8:20am Sep 24, 2011 at 8:20am UTC
I always get a 1 with this:
You always get 1 ?
cout<<"comparison: " <<strcmp;
should be displaying the address of the function strcmp()
I get
Andy
P.S. Note that <string.h> and <cstring> are effectively the same file. The latter just wraps the former in the std namespace.
Topic archived. No new replies allowed.