我们继续看看这个程序
- #include <stdio.h>
- #define MAXTITL 40
- #define MAXAUTL 40
- #define MAXBKS 100 /* 最多可以容纳的书籍数目 */
- struct book { /* 建立book的结构模板 */
- char title[MAXTITL];
- char author[MAXAUTL];
- float value;
- };
- int main (void)
- {
- struct book library[MAXBKS]; /* book 结构数组 */
- int count = 0;
- int index;
- printf ("Plesae enter the book title \n");
- printf ("Press [enter] at thne start of a line to stop \n");
- while (count < MAXBKS && gets(library[count].title) != NULL && library[count].title[0] != '\0')
- {
- printf ("Now enter the author \n");
- gets (library[count].author);
- printf ("Now enter the value \n");
- scanf ("%f", &library[count++].value); /* 这里用count++来转换成下一组信息 */
- while (getchar() != '\n')
- continue; /* 清空输入行 */
- if (count < MAXBKS)
- printf ("Enter then 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");
- return 0;
- }
——————————————————————————————————————————————————
那我可以运行一下(感觉穿不了照片欸 (~ ̄▽ ̄)→))* ̄▽ ̄*)o)手打
Plesae enter the book title
Press [enter] at thne start of a line to stop
My life as a Budgie
Now enter the author
Mack Zackles
Now enter the value
12.95
Enter then next title
.... more ........
Here is the list of your books :
My life as a Budgie by Mack Zackles : $12.95
Thought and unthought Rethought by kindra Schlagmeyer : $43.50
The Business of a Bee by Buster Downsize : $19.25
.......more
——————————————————————————————————————————————————
相比于最开始那个程序的主要变化是,我们插入了一个循环来读取多个输入项。循环式有下面这个while条件开始的:
————while(count < MAXBKS && gets(;ibrary[sount].title) ! = NULL && library[count].title[0] != '\o')——————
我们用gets来读入一个字符串为书名;如果gets检测字符串的第一个字符是否为空字符'\0',也就是判断是否输入了字符,以确保用户在输入回车,影响整个程序的输入
————————while(getchar() != '\n') continue;//清空输入行———————————————————
为什么要这么设定呢?
—我们知道,我们的scanf会忽略掉空格和回车,而这一段代码可以弥补这个问题
你们可以这么理解,你把除了刚刚输入的被valuue读取的价格以外的所有垃圾数据全部不停输入不停继续直到你输入回车,而这些输入的也不会被储存如计算机。也就是只要不是换行符他就会continue继续返回从新输入,这样 我举一个例子:
———清空输入行:
#include<stido.h>
int main ()
{
int i, j;
scanf("%d ", &i);
printf("i = %d\n", i);
\\ while(getchar() != '\n')
\\ continue;
scanf("%d ", &j);
printf("j = %d\n", j);
___________________________________________________________________________________________我们来看看,如果正常来输入的话,也就是说不要注释里的代码,如果我们正确的输入,就会是这样
1
i = 1
2
j = 2
但考虑到如果用户在1后面输入了别的东西zhangsan啊lisi啊等等什么的,你的程序就会崩溃,为什么呢,因为你的scanf相当于只把1输入到了程序而后面的东西放在了一个叫输入流的地方等待下一次被输入到计算机里,也就是说你的j就不用输入了,因为输入流已经有东西等待输入到j里了,因此,就会形成这样的东西
1 zhangsanlisiwangmazi
i = 1
j = -858993460
那也就是说我们需要把输入流里面的东西全部消去,怎么办呢,我们就要使用我们作为注释的那一段语句。什么意思呢,getchar就是等待用户输入一个字符,而如果这个字符不是换行就继续输入,直到我把wangmazi输入完输入换行符才停止循环。,这样gets就可以重新开始了