0

I learnt (self-learning) the basics of structure in C today and wrote this simple code. it is compiling without any error. I know that successful compilation is no guarantee for a bug-free software. While execution, it scans the inputs for two structure variables only and gives erroneous display. for the sake of simplicity I chose a char to store the book name. I am not able to figure out the bug here. could you find one?

#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;
}
4

1 に答える 1

1

( 入力バッファをフラッシュするために)を追加して、「余分な」入力を削除する必要があります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. コンソールからユーザー入力を取得する方法 -- 安全。
于 2012-05-01T03:57:33.867 に答える