我有这个 C 代码:
#include "stdio.h"
main()
{
struct books
{
char name[100],author[100];
int year,copies;
}book1,book2;
printf("Enter details of first book\n");
gets(book1.name);
gets(book1.author);
scanf("%d%d",&book1.year,&book1.copies);
printf("Enter details for second book\n");
gets(book2.name);
gets(book2.author);
scanf("%d%d",&book2.year,&book2.copies);
printf("%s\n%s\n%d\n%d\n",book1.name,book1.author,book1.year,book1.copies);
printf("%s\n%s\n%d\n%d\n",book2.name,book2.author,book2.year,book2.copies);
}
这里发生的事情是它只扫描到第二本书的作者姓名。之后它直接打印输出。
这是我的输入:(前两行是初始 printf 语句)
Enter details of first book
warning: this program uses gets(), which is unsafe.
the c programmign laguagne
dfadsda
3432
23
Enter details for second book
ruby on rails
mark hammers
之后它直接打印输出:
the c programmign laguagne
dfadsda
3432
23
ruby on rails
0
0
这里出了什么问题?我们还可以看到第二本书的名字被分配给作者。
我使用 gcc
作为 Mac OS X ML 上的编译器。
最佳答案
使用fflush(stdin)
在每个输入语句之前。该方法将清除输入缓冲区。
修改后您的代码将是 -
#include "stdio.h"
int main()
{
struct books
{
char name[100],author[100];
int year,copies;
}book1,book2;
printf("Enter details of first book\n");
gets(book1.name);
fflush(stdin);
gets(book1.author);
fflush(stdin);
scanf("%d%d",&book1.year,&book1.copies);
fflush(stdin);
printf("Enter details for second book\n");
gets(book2.name);
fflush(stdin);
gets(book2.author);
fflush(stdin);
scanf("%d%d",&book2.year,&book2.copies);
printf("%s\n%s\n%d\n%d\n",book1.name,book1.author,book1.year,book1.copies);
printf("%s\n%s\n%d\n%d\n",book2.name,book2.author,book2.year,book2.copies);
return 0;
}
您可以查看 fflush()
的详细信息here .罢工>
更新: 在 scanf() 语句之后,您需要刷新输入缓冲区。 fflush() 方法在这里没有用,因为它仅为输出流定义。您可以在每个 scanf() 行之后使用单行代码来使用部分读取的行的其余部分,例如 -
while((c = getchar()) != '\n' && c != EOF);
你的代码将是:
#include "stdio.h"
int main()
{
struct books
{
char name[100],author[100];
int year,copies;
}book1,book2;
char c;
printf("Enter details of first book\n");
gets(book1.name);
gets(book1.author);
scanf("%d%d",&book1.year,&book1.copies);
while((c = getchar()) != '\n' && c != EOF);
printf("Enter details for second book\n");
gets(book2.name);
gets(book2.author);
scanf("%d%d",&book2.year,&book2.copies);
while((c = getchar()) != '\n' && c != EOF);
printf("%s\n%s\n%d\n%d\n",book1.name,book1.author,book1.year,book1.copies);
printf("%s\n%s\n%d\n%d\n",book2.name,book2.author,book2.year,book2.copies);
return 0;
}
输出:
Enter details of first book
warning: this program uses gets(), which is unsafe.
sadsadas
asa
12
34
Enter details for second book
zxczxc
sds
23
22
sadsadas
asa
12
34
zxczxc
sds
23
22
关于C 结构不扫描所有输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19376077/