Search code examples
cprintfstrtokstrcmpstrsep

Trying to print the last element in string of numbers


I have this code in C, where I will be inputting a string of numbers separated by spaces, and splitting it with strsep. If I input a string like "1 2", and set strcmp to look for a number before the last element, the code works, but if I set strcmp to look for the last element, the code fails. Can you suggest any fixes?

char *string = malloc(1028), *found;
  if (fgets(string, 1028, stdin) != NULL) {
    while ((found = strsep(&string, " ")) != NULL) {
      if (strcmp(found, "2") == 0) {
        printf("%s\n", found);
      }
    }
  }

Solution

  • It's because the last element that found points to is including the new line character. So you'd either have to add the new line to strcmp like so: strcmp(found, "2\n") (assuming 2 was your last element) or when you call strsep you need to tokenize on both the space and new line character: strsep(&string, " \n").

    Complete solution:

    char *string = malloc(1028);
    if (string) {
      if (fgets(string, 1028, stdin) != NULL) {
        char *p = string, *found = string;
        while ((found = strsep(&p, " \n")) != NULL) {
          if (strcmp(found, "1") == 0) {
            printf("%s\n", found);
          }
        }
      }
      free(string);
    }
    

    A few things to observe: The string pointer is modified by the strsep function so I've updated the code to use an intermediate variable p. I've also updated the code to validate the allocation was successful and then free it at the end. Depending upon your system requirements, you could consider forgoing the heap and allocating string on the stack.