程序不会在第二次 scanf() 读取 [英] program wont read at second scanf()

查看:67
本文介绍了程序不会在第二次 scanf() 读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白我哪里出错了.它不会在第二个 scanf() 读取,只是跳到下一行.

I dont understand where I went wrong. It does not read at second scanf() just skips on to the next line.

#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() 在输入流中留下一个换行符,当你读取一个字符时,它会被下一个 scanf() 使用.

Your first scanf() leaves a newline in the input stream which is consumed by the next scanf() when you read a char.

改变

scanf ("%c",&read_y);

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

这将忽略所有空格.

一般来说,避免使用 scanf() 来读取输入(尤其是像这里那样混合不同格式时).而是使用 fgets() 并使用 sscanf().

In general, avoid scanf() for reading inputs (especially when mixing different formats as do here). Instead use fgets() and parse it using sscanf().

这篇关于程序不会在第二次 scanf() 读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆