copy3.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /* copy3.c -- strncpy() demo */
  2. #include <stdio.h>
  3. #include <string.h> /* declares strncpy() */
  4. #define SIZE 40
  5. #define TARGSIZE 7
  6. #define LIM 5
  7. char * s_gets(char * st, int n);
  8. int main(void)
  9. {
  10. char qwords[LIM][TARGSIZE];
  11. char temp[SIZE];
  12. int i = 0;
  13. printf("Enter %d words beginning with q:\n", LIM);
  14. while (i < LIM && s_gets(temp, SIZE))
  15. {
  16. if (temp[0] != 'q')
  17. printf("%s doesn't begin with q!\n", temp);
  18. else
  19. {
  20. strncpy(qwords[i], temp, TARGSIZE - 1);
  21. qwords[i][TARGSIZE - 1] = '\0';
  22. i++;
  23. }
  24. }
  25. puts("Here are the words accepted:");
  26. for (i = 0; i < LIM; i++)
  27. puts(qwords[i]);
  28. return 0;
  29. }
  30. char * s_gets(char * st, int n)
  31. {
  32. char * ret_val;
  33. int i = 0;
  34. ret_val = fgets(st, n, stdin);
  35. if (ret_val)
  36. {
  37. while (st[i] != '\n' && st[i] != '\0')
  38. i++;
  39. if (st[i] == '\n')
  40. st[i] = '\0';
  41. else // must have words[i] == '\0'
  42. while (getchar() != '\n')
  43. continue;
  44. }
  45. return ret_val;
  46. }