2013-06-19 32 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