1
0

names1.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* names1.c -- uses pointers to a structure */
  2. #include <stdio.h>
  3. #include <string.h>
  4. #define NLEN 30
  5. struct namect {
  6. char fname[NLEN];
  7. char lname[NLEN];
  8. int letters;
  9. };
  10. void getinfo(struct namect *);
  11. void makeinfo(struct namect *);
  12. void showinfo(const struct namect *);
  13. char * s_gets(char * st, int n);
  14. int main(void)
  15. {
  16. struct namect person;
  17. getinfo(&person);
  18. makeinfo(&person);
  19. showinfo(&person);
  20. return 0;
  21. }
  22. void getinfo (struct namect * pst)
  23. {
  24. printf("Please enter your first name.\n");
  25. s_gets(pst->fname, NLEN);
  26. printf("Please enter your last name.\n");
  27. s_gets(pst->lname, NLEN);
  28. }
  29. void makeinfo (struct namect * pst)
  30. {
  31. pst->letters = strlen(pst->fname) +
  32. strlen(pst->lname);
  33. }
  34. void showinfo (const struct namect * pst)
  35. {
  36. printf("%s %s, your name contains %d letters.\n",
  37. pst->fname, pst->lname, pst->letters);
  38. }
  39. char * s_gets(char * st, int n)
  40. {
  41. char * ret_val;
  42. char * find;
  43. ret_val = fgets(st, n, stdin);
  44. if (ret_val)
  45. {
  46. find = strchr(st, '\n'); // look for newline
  47. if (find) // if the address is not NULL,
  48. *find = '\0'; // place a null character there
  49. else
  50. while (getchar() != '\n')
  51. continue; // dispose of rest of line
  52. }
  53. return ret_val;
  54. }