程序在第二个scanf()处无法读取

3

我不明白我的错误在哪里。第二个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;
}

附注:不要使用goto语句。 - Ben Ruijl
4
“goto do_again;” 的翻译是 “跳转至 do_again 标签;”。“We are in 21st century !!!!!” 的意思是 “我们处于21世纪!!!”。 - AllTooSir
为什么我不应该使用goto? - Rahul R
1
@TheNewIdiot:“goto do_again; 我们已经进入了21世纪!!!!” 你的意思是什么?为什么不应该使用goto? - Rahul R
因为http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html - Dronacharya
因为http://xkcd.com/292/。 - abelenky
2个回答

10

您的第一个scanf()在输入流中留下了一个换行符,当您读取一个字符时,它被下一个scanf()使用。

更改为:

scanf ("%c",&read_y);

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

忽略所有空格。


一般情况下,避免使用scanf()读取输入(尤其是在混合不同格式时)。而使用 fgets()函数读取输入,并使用sscanf()函数解析它。


2
没有什么阻止你使用scanf()。只是使用它可能会导致格式问题,因为scanf()不能很好地处理输入失败。 - P.P

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)

会把它加入我的笔记中。我是新手正在学习。谢谢你的帮助。 - Rahul R
fflush(stdin) 是未定义行为,因为它仅适用于输出流。 - lost_in_the_source

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接