2010-07-06 110 views
1
/* It is not entering data into the third scanf() statement .*/ 

#include<stdio.h> 
#include<conio.h> 
#include<string.h> 
void main(void) 
{ 
    struct book 
    { 
     char name; 
     int pages; 
     float price; 

    }; 
    struct book a1,a2,a3,a4; 
    printf("Enter data into 3 books\n"); 
    scanf("%c %d %f",&a1.name,&a1.pages,&a1.price); 
    scanf("%c %d %f",&a2.name,&a2.pages,&a2.price); 
    scanf("%c %d %f",&a3.name,&a3.pages,&a3.price); 
    printf(" you entered:\n"); 
    printf("\n%c %d %f",a1.name,a1.pages,a1.price); 
    printf("\n%c %d %f",a2.name,a2.pages,a2.price); 
    printf("\n%c %d %f",a3.name,a3.pages,a3.price); 

    getch(); 
} 
+0

不要對'string'條目使用'scanf()'。改用'fgets()'。 – 2010-07-06 13:39:28

+0

他沒有使用'scanf'作爲'string'條目。 – 2010-07-06 13:44:46

+0

@ el.pescado:他編輯了他的帖子。他將'char name [100]'改爲'char name' – 2010-07-06 13:47:25

回答

2

你想要一個字符串作爲一個名字,而你給一個%c說明符的輸入需要一個字符。

所以要麼使用%s作爲字符串輸入。

或更好地利用像一些字符串函數gets()函數

gets (a1.name); 
scanf (%d %f",&a1.pages,&a1.price); 

並再次提醒,你必須與字符串(字符數組)的大小小心,以避免棧溢出。

謝謝

Alok.Kr.

4

你想用字符串,而不是單個字符:

int main(void) 
{ 
    struct book 
    { 
     char name[100]; 
     int pages; 
     float price; 

    }; 
    struct book a1,a2,a3,a4; 
    printf("Enter data into 3 books\n"); 
    scanf("%s %d %f",&a1.name,&a1.pages,&a1.price); 
    scanf("%s %d %f",&a2.name,&a2.pages,&a2.price); 
    scanf("%s %d %f",&a3.name,&a3.pages,&a3.price); 
    printf(" you entered:\n"); 
    printf("%s %d %f\n",a1.name,a1.pages,a1.price); 
    printf("%s %d %f\n",a2.name,a2.pages,a2.price); 
    printf("%s %d %f\n",a3.name,a3.pages,a3.price); 

    return 0; 
} 

但要注意,這是容易出現緩衝區溢出,並不會與包含空格的書名正確對待。