C 结构代码正在编译但不运行



我今天学习(自学)C语言结构的基础知识,并编写了这个简单的代码。 它正在编译而没有任何错误。我知道成功的编译并不能保证软件没有错误。执行时,它仅扫描两个结构变量的输入,并给出错误的显示。为了简单起见,我选择了一个字符来存储书名。我无法弄清楚这里的错误。你能找到一个吗?

#include<stdio.h>
int main(void)
{
    struct book
    {   char name;
        float price;
        int pages;
    };
    struct book b[3];
    int i;
    for (i = 0; i <= 2; i++){
        printf("nEnter name, price and pages ");
        scanf("%c %f %i", &b[i].name, &b[i].price, &b[i].pages);
    }
    for (i = 0; i <= 2; i++)
        printf("n%c %f %i",b[i].name, b[i].price, b[i].pages);
    return 0;
}

您需要通过添加while((ch=getchar())!='n');来删除"额外"输入(以刷新输入缓冲区)(请声明char ch;):

for (i = 0; i <= 2; i++){
   printf("nEnter name, price and pages ");
   scanf("%c %f %i",&b[i].name,&b[i].price, &b[i].pages);
   while((ch=getchar())!='n'); //eat the chars
 }

教程/帖子:

  1. "刷新"输入流
  2. 如何安全地从控制台获取用户输入。

最新更新