Search code examples
cstringpointersstring.hc-str

Strchr and strrchr returning same result


For some reason, whether I try strchr or strrchr, I get the same value returned. I have no idea why.

Here is the segment of code giving me trouble:

      printf("Enter a data point (-1 to stop input):\n");
      fgets(input, 50, stdin);
      char *name = strrchr(input, ',');
      if(name)
      {
         printf("%s", name);
      }

The input is Jane Austen, 6, and I am trying to separate it into two strings: one before the comma and one after the comma. However, my use of strrchr(input, ','); or strchr(input, ','); seems pointless, as my output is ALWAYS , 6. Can someone explain why?


Solution

  • It sounds like you want strtok instead:

    char *name = strtok(input, ",");
    char *value = strtok(NULL, ",");