2012-06-22 34 views
0

在下面的程序中,我沒有從printf得到值。visual studio中的struct程序

#include<stdio.h> 

int main() 
{ 
    struct book 
    { 
     char name; 
    float price; 
    int pages; 
    }; 
    struct book b1,b2,b3; 

    printf("enter names prices & no. of pages of 3 books\n"); 
    scanf("%c %f %d",&b1.name,&b1.price,&b1.pages); 
    fflush(stdin); 
    scanf("%c %f %d",&b2.name,&b2.price,&b2.pages); 
    fflush(stdin); 
    scanf("%c %f %d",&b3.name,&b3.price,&b3.pages); 
    fflush(stdin); 
    printf("and this is what you entered\n"); 
    printf("%c %f %d",&b1.name,&b1.price,&b1.pages); 
    printf("%c %f %d",&b2.name,&b2.price,&b2.pages); 
    printf("%c %f %d",&b3.name,&b3.price,&b3.pages); 
    return 0; 
} 

這個輸出我得到

enter names prices & no. of pages of 3 books 
a 34.6 23 
b 23.4 34 
c 63.5 23 

and this is what you entered 

0.000000 0∞ 0.000000 0╪ 0.000000 0Press any key to continue . . . 

爲什麼不輸出匹配輸入?

+1

大多數'printf()'格式最後都需要換行符,除非您有意識地構建單個多行調用輸出到'printf()'。而且,如果不包含換行符或使用'fflush(stdout)'或'fflush(0)',則可能看不到輸出。 –

回答

3
printf("%c %f %d",&b1.name,&b1.price,&b1.pages); 
printf("%c %f %d",&b2.name,&b2.price,&b2.pages); 
printf("%c %f %d",&b3.name,&b3.price,&b3.pages); 

太複製和粘貼methinks。當printf預計爲char s時,您正在傳遞指針,對於浮點數和整數都是一樣的。

您將這些變量的地址傳遞給scanf,以便函數可以更改它們的值。當你使用%d,%f%cprintf需要一個int(不是指向int的指針),一個float(不是指向float的指針)和一個char(不是指向char的指針)。

+0

thnx,我刪除&在printf語句,現在它的工作正常。 –

2

有多個問題與您的程序:

  • char適合單個字符。它不足以存儲書的標題。
  • 您傳遞地址scanf,但你值傳遞給printf(即沒有0​​上printf的參數,除了可能對%p的參數)
  • 你並不需要fflush你的輸入流 - 它沒有任何效果。

我想你應該改變char namechar name[101](或任何其他最大尺寸您願意),併爲scanf("%c...", &b1.name,...)scanf("%100s...", b1.name,...)。請注意0​​中的符號&是如何丟失的:這是因爲當傳遞給C中的函數時,數組衰減爲指針。

+0

是的,我做到了。抱歉。 –

+0

@JonathanLeffler好吧,我刪除了評論:) – dasblinkenlight

相關問題