程序不会在第二次扫描时读取()

时间:2013-06-19 07:22:42

标签: c 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;
}

2 个答案:

答案 0 :(得分:10)

你的第一个scanf()在输入流中留下一个换行符,当你读取一个char时,下一个scanf()会使用该换行符。

更改

scanf ("%c",&read_y);

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

将忽略所有空格。


通常,请避免使用scanf()来读取输入(特别是在混合使用不同格式时)。而是使用 fgets() 并使用sscanf()解析它。

答案 1 :(得分: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)