-1

So I had this program. It should print out true since ret is "Point", just that I got it from strstr, and I am comparing it to the string "Point". For some mysterious reason, they are not the same strings. What is going on? Here is the code:

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

int main () {
   char *ret;

   ret = strstr("TutorialsPoint", "Point");
   
   if (strcmp(ret,"Point")) {
       printf("Strings are equal\n");
   } else {
       printf("strings are not equal\n");
   }

   printf("The substring is: %s\n", ret);
   
   return(0);
}
  • 3
    Have you read the [man page for strcmp](https://man7.org/linux/man-pages/man3/strcmp.3.html)? What does it return when two strings are equal? – costaparas Jan 04 '21 at 12:05
  • Does this answer your question? [Comparing two strings in C?](https://stackoverflow.com/questions/14232990/comparing-two-strings-in-c) – costaparas Jan 04 '21 at 12:07
  • @costaparas Be nice. The return value of `strcmp()` is perverse and more than a bit confusing for beginners without C experience. ***And*** bugs like this are hard enough to spot even for experienced developers. – Andrew Henle Jan 04 '21 at 12:11
  • @andrew-henle sure I agree, `strcmp` didn't have the best design unfortunately **and** I'm sure everyone has made this mistake at least a few times. My comment was just to remind the OP of the documentation, didn't mean anything by it. – costaparas Jan 04 '21 at 12:15
  • 1
    @AndrewHenle Stack Overflow isn't a replacement for reading any documentation for a library function that doesn't seem to do what you expect. – Blastfurnace Jan 04 '21 at 12:16
  • Note that if the first string had been `"OnePointTwo"` there would be no match because the substring within has no string terminator. – Weather Vane Jan 04 '21 at 12:32
  • @Blastfurnace Read my entire comment. It's not just the return value is unexpected. Spotting bugs like that is ***hard*** even for experienced programmers who have programmed in C for decades. – Andrew Henle Jan 04 '21 at 12:32
  • 1
    @AndrewHenle Telling someone that documentation exists isn't "blathering". Documentation is a good **starting point** to understand the tools you use. If that doesn't help then reaching out to SO is also good. – Blastfurnace Jan 04 '21 at 12:48

1 Answers1

2

strcmp returns 0 if the strings are equal : you should write :

if(strcmp(ret, "Point") == 0){
    printf("equal");
}
else{
    printf("not equal");
}
limserhane
  • 1,022
  • 1
  • 6
  • 17