2012-01-31 243 views
1

剛開始學習C.
如果我在Dev-C++中編譯下面的代碼,程序運行良好。
如果我在Xcode 3.2.6中編譯它看起來像在屏幕截圖中。
我在Xcode中嘗試了不同的編譯器設置,但行爲仍然相同。
對此有何想法?不同的行爲xcode和Dev-C++

#include <stdio.h> 
#include <stdlib.h> 

int main(int argc, char *argv[]) 
{ 
    char artist[30]; 
    char album[30]; 
    int tracks; 
    char albumsingle; 
    float price; 

    printf("Please enter CD informations below. \n \n"); 

    printf("enter cd artist: "); 
    scanf("%[^\n]", artist); 

    printf("enter cd title: "); 
    fflush(stdin); 
    scanf("%[^\n]", album); 

    printf("enter no. of tracks: "); 
    fflush(stdin); 
    scanf("%d", &tracks); 

    printf("enter a for album s for single: "); 
    fflush(stdin); 
    scanf("%c", &albumsingle); 

    printf("enter price: "); 
    fflush(stdin); 
    scanf("%f", &price); 



    printf("\n\n\nartist: %s\n", artist); 
    printf("album: %s\n", album); 
    printf("track no.: %d\n", tracks); 
    if (albumsingle == 'a'){ 
     printf("cd type: album\n"); 
    } else { 
     printf("cd type: single\n"); 
    } 

    printf("price: %.2f EUR\n\n", price);         

    system("PAUSE"); 
    return 0; 
} 
+0

什麼截圖?不要添加屏幕截圖,只需將錯誤消息添加到您的問題中,或者添加預期的輸出和實際輸出。 – 2012-01-31 13:54:39

回答

3
fflush(stdin); 

導致的未定義行爲,因此你的程序顯示了不同的編譯器不同的行爲。

參考C標準:

int fflush(FILE *ostream); 

ostream的點到輸出流或其中的最近操作不是輸入的更新流,fflush函數導致任何未寫入的數據爲被傳遞的是流到主機環境寫入文件; 否則,行爲是不確定的。

+1

這是正確的答案。看起來這兩種編譯器符合C標準並且行爲正確,因爲當程序調用未定義的行爲時,它們都會給出任何類型的隨機結果。另請參閱[C常見問題](http://c-faq.com/stdio/stdinflush.html)。 – Lundin 2012-01-31 14:24:21

4

我的猜測是它與system("PAUSE");聲明有關。 Xcode在OSX上使用,這是一個UNIX變體,並且沒有命令pause

相反,爲什麼不只是要求用戶手動按下回車鍵?像這樣:

printf("Press the ENTER key to continue.\n"); 
int c; 
do 
{ 
    c = fgetc(stdin); 
} while (c != '\n' && c != EOF); 

它具有在大多數系統上工作的優勢。

0

PAUSE是一個Windows,而不是一個Unix命令......所以這將無法在Mac上運行。如果您只是想在最後暫停程序,請使用類似getchar()的內容。

0

包含頭文件Conio.h並使用getch()函數,只要您想要屏幕。