簡體   English   中英

程序不會在第二次掃描時讀取()

[英]program wont read at second scanf()

我不明白我哪里出錯了。 它不會在第二次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;
}

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

更改

scanf ("%c",&read_y);

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

這將忽略所有空格。


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

你可以這樣做:

#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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM