join_chk.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /* join_chk.c -- joins two strings, check size first */
  2. #include <stdio.h>
  3. #include <string.h>
  4. #define SIZE 30
  5. #define BUGSIZE 13
  6. char * s_gets(char * st, int n);
  7. int main(void)
  8. {
  9. char flower[SIZE];
  10. char addon[] = "s smell like old shoes.";
  11. char bug[BUGSIZE];
  12. int available;
  13. puts("What is your favorite flower?");
  14. s_gets(flower, SIZE);
  15. if ((strlen(addon) + strlen(flower) + 1) <= SIZE)
  16. strcat(flower, addon);
  17. puts(flower);
  18. puts("What is your favorite bug?");
  19. s_gets(bug, BUGSIZE);
  20. available = BUGSIZE - strlen(bug) - 1;
  21. strncat(bug, addon, available);
  22. puts(bug);
  23. return 0;
  24. }
  25. char * s_gets(char * st, int n)
  26. {
  27. char * ret_val;
  28. int i = 0;
  29. ret_val = fgets(st, n, stdin);
  30. if (ret_val)
  31. {
  32. while (st[i] != '\n' && st[i] != '\0')
  33. i++;
  34. if (st[i] == '\n')
  35. st[i] = '\0';
  36. else // must have words[i] == '\0'
  37. while (getchar() != '\n')
  38. continue;
  39. }
  40. return ret_val;
  41. }