*---------------------------------
names1.c -- 使用指向结构的指针
---------------------------------*/ #include <stdio.h>
#include <string.h> #define NLEN 30 struct namect
{
char fname[NLEN];
char lname[NLEN];
int letters;
}; void getinfo(struct namect *);
void makeinfo(struct namect *);
void showinfo(const struct namect *);
char* s_gets(char *st, int n); int main()
{
struct namect person; getinfo(&person);
makeinfo(&person);
showinfo(&person); return ;
} void getinfo(struct namect *pst)
{
printf("Please enter your first name.\n"); s_gets(pst->fname, NLEN); printf("Please enter your last name.\n"); s_gets(pst->lname, NLEN);
} void makeinfo(struct namect *pst)
{
pst->letters = strlen(pst->fname) + strlen(pst->lname);
} void showinfo(const struct namect *pst)
{
printf("%s %s, your name contains %d letters.\n"
, pst->fname, pst->lname, pst->letters);
} char* s_gets(char *st, int n)
{
char *ret_val;
char *find; if (ret_val = fgets(st, n, stdin))
{
if (find = strchr(st, '\n')) //查找换行符
*find = '\0';
else
while (getchar() != '\n') continue; //处理输入行的剩余字符
} return ret_val;
}
names1.c
/*------------------------------
names2.c -- 传递并返回结构
------------------------------*/ #include <stdio.h>
#include <string.h> #define NLEN 30 struct namect
{
char fname[NLEN];
char lname[NLEN];
int letters;
}; struct namect getinfo(void);
struct namect makeinfo(struct namect);
void showinfo(struct namect);
char* s_gets(char *st, int n); int main()
{
struct namect person; person = getinfo();
person = makeinfo(person);
showinfo(person); return ;
} struct namect getinfo(void)
{
struct namect temp; printf("Please enter your first name.\n"); s_gets(temp.fname, NLEN); printf("Please enter your last name.\n"); s_gets(temp.lname, NLEN); return temp;
} struct namect makeinfo(struct namect info)
{
info.letters = strlen(info.fname) + strlen(info.lname);
return info;
} void showinfo(struct namect info)
{
printf("%s %s, your name contains %d letters.\n"
, info.fname, info.lname, info.letters);
} char* s_gets(char *st, int n)
{
char *ret_val;
char *find; if (ret_val = fgets(st, n, stdin))
{
if (find = strchr(st, '\n')) //查找换行符,如果找到换行符,将换行符成空字符
*find = '\0';
else
while (getchar() != '\n') continue; //处理输入行的剩余部分
} return ret_val;
}
names2.c