C 一直运行直到用户输入n退出的程序

C 一直运行直到用户输入n退出的程序,c,loops,C,Loops,我正在处理一个任务,允许用户输入“类型”和“重量”,它将显示成本。这是代码。我希望它一直运行,直到用户输入“n” main() { char type,chr; float cost,weight; do { printf("Insert the type of fish: "); /*inputs type and weight*/ scanf("%c",&type); printf("i

我正在处理一个任务,允许用户输入“类型”和“重量”,它将显示成本。这是代码。我希望它一直运行,直到用户输入“n”

main()
{   
    char type,chr;
    float cost,weight;

    do
    {   
        printf("Insert the type of fish: ");  /*inputs type and weight*/ 
        scanf("%c",&type);
        printf("insert weight: ");
        scanf("%f",&weight);

        switch(type)                        
        {
            case 'K':
            case 'k':
                cost=weight*9.00;
                break;
            case 'R':
            case 'r':
                cost=weight*10.00;
                break;
            case 'S':
            case 's':
                cost=weight*12.00;
                break;
            case 'G':
            case 'g':
                cost=weight*8.00;
                break;
            case 'T':
            case 't':
                cost=weight*15.00;
                break;
            default :
                printf("Invalid type\n");
        }
        printf("The cost of fish is:%.2f \n",cost);
        printf("Do you want to continue?Y/N: ");
        scanf(" %c",&chr);
    }
    while(chr == 'Y' || chr == 'y');
}
我使用了
do..while
循环,它工作得很好,直到我键入“y”并且无法输入类型


从stdin流读取类型假定您确切知道流中的下一个内容。正如Streeragh所提到的,您可能有一个换行符作为下一个输入字符。您可以通过转储chr是什么来区分这一点(尝试使用十六进制,如%0x)。上述文章还提供了很好的建议:将文本作为%s输入(或使用readline),然后解析出输入。看看斯特托克。还要注意,stdin可以从管道重定向(即out.exeHi!欢迎来到StackOverflow!我建议你通过以下方式来提高你的问题的质量:使用正确的格式/缩进,尽量减少标题。另请参见。使用
fgets()
(可能后跟
sscanf()
)进行用户输入
scanf()
在错误处理/恢复方面相当糟糕,而且在管理空白方面也很笨拙。您当前的问题是
scanf(“%c”、&chr)之后的输入缓冲区中仍然存在问题。我认为这是一个跳过scanf的问题。请相信这个答案@SreeraghAR我认为这似乎是问题所在,我所要做的就是在“%c”中添加空格。非常感谢!!!!