输出示例
please enter your first name:
wang
please enter your last name:
fei
wang fei , your name contains 7 letters.
【结构作为参数传递并返回结构】
#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 0;
}
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;
}
//将结构person作为参数,创建一个新的结构info并将person的值拷贝到此结构
struct namect makeinfo(struct namect info)
{
info.letters = strlen(info.fname) + strlen(info.lname);
//统计完字母个数后,结果保存在info中,通过return 将info的值拷贝到person中,即返回一个结构
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;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
【传递结构的地址】
#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);
getchar();
return 0;
}
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;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}