Home > Back-end >  Codewars Grasshopper - Personalized Message c
Codewars Grasshopper - Personalized Message c

Time:09-18

I've started using Codewars to learn C and this problem is giving me issues. When I attempt to submit the answer I get errors against their test cases. I'm not sure what I did wrong or left out but any advice would be appreciated.

Errors:

"The expression (as strings) (greet(danielToo, "Daniel")) == ("Hello boss") is false: actual=Hello guest expected=Hello boss."

"The expression strcmp(greet(second, secondCopy), greetChecker(second, second)) == 0 is false."

Instructions:

"Create a function that gives a personalized greeting. This function takes two parameters: name and owner." Use conditionals to return the proper message:

name equals owner 'Hello boss'

otherwise 'Hello guest'

My code:

const char* greet(const char *name, const char *owner) {
  if (name == owner)
    {
      return "Hello boss";
    }
    else
    {
      return "Hello guest";
    }
  return "";
}

Test cases:

#include <criterion/criterion.h>

const char* greet(const char *name, const char *owner);

Test(ExampleTests, ShouldPassAllTheTestsProvided) {
    cr_assert_str_eq(greet("Daniel", "Daniel"), "Hello boss");
    cr_assert_str_eq(greet("Greg", "Daniel"), "Hello guest");
    static const char danielToo[] = "Daniel";
    cr_assert_str_eq(greet(danielToo, "Daniel"), "Hello boss");
    cr_assert_str_eq(greet("Cat", "Catherine"), "Hello guest", "Cat is not Catherine");
    cr_assert_str_eq(greet("Catherine", "Cat"), "Hello guest", "Caterine is not Cat");
}

CodePudding user response:

Your checking if the two values point to the same place in memory, you should change your if condition to strcmp(name,owner) == 0. This function will return 0 if the two passed arguments are equal. You can learn more about it here https://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm

CodePudding user response:

The comparison name == owner checks whether the pointers are the same, which is not a necessary condition for the strings to be equal.

See also, e.g., https://stackoverflow.com/a/8004250/13134095.

  •  Tags:  
  • c
  • Related