示例
#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 */
#define MAXBKS 100 /* 书籍的最大数量 */
/* 声明结构(模板) */
struct book {
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
int main(int argc, char* argv[])
{
/*
分配的栈内存太多,可能会报栈溢出错误。可设置编译器选项增加栈大小。
*/
struct book library[MAXBKS]; // 声明结构体数组
int count = 0;
int index;
printf("Please enter the book title.\n");
printf("Press [enter] at the start of a line to stop.\n");
while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL
&& library[count].title[0] != '\0')
{
printf("Now enter the author.\n");
s_gets(library[count].author, MAXAUTL);
printf("Now enter the value.\n");
//scanf()函数遇到空格或换行符就会结束读取
scanf("%f", &library[count++].value);
while (getchar() != '\n')
continue; // 清理输入行
if (count < MAXBKS)
printf("Enter the next title.\n");
}
if (count > 0)
{
printf("Here is the list of your books:\n");
for (index = 0; index < count; index++)
{
printf("%s by %s: $%.2f\n", library[index].title,
library[index].author, library[index].value);
}
}
else
{
printf("No books? Too bad.\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;
}
运行测试