示例
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdbool.h>
char* s_gets(char *st, int n);
#define MAXTITL 41 /* 书名的最大长度 + 1 */
#define MAXAUTL 31 /* 作者姓名的最大长度 + 1 */
// 结构声明可以放在所有函数外部,也可以放在函数内部
/* 声明结构(模板) */
struct book {
//定义成员(member)或字段(field)
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
/*
struct book {
char title[MAXTITL];
char author[MAXAUTL];
float value;
} library; //也可以这样声明结构变量
*/
/*
struct { //省略结构标记
char title[MAXTITL];
char author[MAXAUTL];
float value;
} library; //也可以这样声明结构变量
*/
int main(int argc, char* argv[])
{
//struct book library; // 声明结构体变量
/*
初始化一个静态存储期的结构,初始化列表中的值必须是常量。
初始化一个自动存储期的结构,初始化列表中的值可以不是常量。
*/
struct book library = { // 声明结构体变量的同时初始化成员
"The Pious Pirate and the Devious Damsel",
"Renee Vivotte",
1.95f
};
/* 结构的初始化器 (也被称为标记化结构初始化语法)
struct book library = {
.title = "The Pious Pirate and the Devious Damsel",
.author = "Renee Vivotte",
.value = 1.95
};
*/
/* 普通初始化器 与 指定初始化器 混合使用
struct book library = { // 声明结构体变量的同时初始化成员
.value = 1.95,
.author = "Renee Vivotte",
2.85 //value值又被设成了2.85, 在结构体声明中因为value跟在author之后
};*/
printf("Please enter the book title.\n");
s_gets(library.title, MAXTITL);
printf("Now enter the author.\n");
s_gets(library.author, MAXAUTL);
printf("Now enter the value.\n");
scanf("%f", &library.value);
printf("%s by %s: $%.2f\n", library.title, library.author, library.value);
printf("%s: \"%s\" ($%.2f)\n", library.author, library.title, library.value);
printf("Done.\n");
system("pause");
return 0;
}
// 自己实现读取函数
char* s_gets(char* st, int n)
{
char* ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val) //即,ret_val != NULL
{
while (st[i] != '\n' && st[i] != '\0')
i++;
if (st[i] == '\n')
st[i] = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
运行测试