gpt4 book ai didi

C 结构不扫描所有输入

转载 作者:行者123 更新时间:2023-12-04 04:38:07 28 4
gpt4 key购买 nike

我有这个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com