Advertisement
STANAANDREY

strchrtok

Jan 3rd, 2023
858
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.78 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdbool.h>
  5. #define NMAX 100
  6. #define SEP ','
  7.  
  8. int main(void) {
  9.   static char s[NMAX];
  10.   if (fgets(s, NMAX, stdin) == NULL) {
  11.     perror("");
  12.     exit(EXIT_FAILURE);
  13.   }
  14.   s[strlen(s) - 1] = 0;
  15.  
  16.   char *p1 = s, *p2 = NULL;
  17.   bool found = true;
  18.   while (found) {
  19.     char *s = NULL;
  20.     p2 = strchr(p1, SEP);
  21.     if (p2) {
  22.       int len = p2 - p1 + 1;
  23.       s = malloc(sizeof(char) * len);
  24.       strncpy(s, p1, len - 1);
  25.       s[len - 1] = 0;
  26.       p1 = p2 + 1;
  27.     } else {
  28.       int len = strlen(p1) + 1;
  29.       s = malloc(sizeof(char) * len);
  30.       strcpy(s, p1);
  31.       found = false;
  32.     }
  33.  
  34.     if (!*s) {
  35.       free(s);
  36.       continue;
  37.     }
  38.    
  39.     puts(s);
  40.     free(s);
  41.   }
  42.   return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement