2013-06-19 31 views
3

我不明白我出錯的地方。它不會在第二個scanf()只讀跳到下一行。程序不會在第二個scanf()讀取()

#include <stdio.h> 
#define PI 3.14 

int main() 
{ 
    int y='y', choice,radius; 
    char read_y; 
    float area, circum; 

do_again: 
    printf("Enter the radius for the circle to calculate area and circumfrence \n"); 
    scanf("%d",&radius); 
    area = (float)radius*(float)radius*PI; 
    circum = 2*(float)radius*PI; 

    printf("The radius of the circle is %d for which the area is %8.4f and circumfrence is %8.4f \n", radius, area, circum); 

    printf("Please enter 'y' if you want to do another calculation\n"); 
    scanf ("%c",&read_y); 
    choice=read_y; 
    if (choice==y) 
     goto do_again; 
    else 
     printf("good bye"); 
    return 0; 
} 
+0

邊注:請不要使用goto的 –

+4

'轉到do_again;'我們在二十一世紀! ! – NINCOMPOOP

+0

爲什麼我不應該使用goto –

回答

10

您的第一個scanf()在輸入流中留下了一個換行符,當您讀取一個char時,它會被下一個scanf()使用。

變化

scanf ("%c",&read_y); 

scanf (" %c",&read_y); // Notice the whitespace 

這會忽略所有空格。


通常,避免scanf()讀取輸入(特別是在混合不同格式時)。請使用fgets()並使用sscanf()解析它。

+0

是的,它工作..非常感謝 –

+0

如果我在整個單一格式去我們可以使用scanf()? –

+2

沒有什麼能阻止你使用scanf()。只是使用它可能導致格式問題,因爲scanf()不能很好地處理輸入失敗。 –

1

,你可以這樣做:

#include <stdlib.h> 
#define PI 3.14 

void clear_buffer(void); 

int main() 
{ 
    int y='y',choice,radius; 
    char read_y; 
    float area, circum; 
    do_again: 
     printf("Enter the radius for the circle to calculate area and circumfrence \n");   
     scanf("%d",&radius);   
     area = (float)radius*(float)radius*PI; 
     circum = 2*(float)radius*PI;  
     printf("The radius of the circle is %d for which the area is %8.4f and circumfrence is %8.4f \n", radius, area, circum); 
     printf("Please enter 'y' if you want to do another calculation\n"); 
     clear_buffer(); 
     scanf("%c",&read_y);    
     choice=read_y;  
    if (choice==y) 
     goto do_again; 
    else 
     printf("good bye\n"); 
    return 0; 
} 

void clear_buffer(void) 
{ 
    int ch; 

    while((ch = getchar()) != '\n' && ch != EOF); 
} 

,或者你可以scanf函數之前寫fflush(STDIN)

+0

將它添加到我的筆記..我是新的commer學習..感謝幫助 –

+0

fflush(stdin)是未定義的行爲,因爲它只是爲輸出流定義 – stackptr