【问题标题】:Program that keeps running until the user inputs n to exit一直运行直到用户输入 n 退出的程序
【发布时间】:2018-09-20 15:06:30
【问题描述】:

我正在处理一项允许用户输入“类型”和“重量”的任务,它会显示成本。这是代码。我希望它一直运行直到用户输入“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”并且我无法输入类型。

【问题讨论】:

  • 嗨!欢迎来到 StackOverflow!我建议您通过以下方式提高问题的质量:使用正确的格式/缩进将标题保持在最低限度。另请参阅How do I ask a good question?
  • 使用fgets()(可能后跟sscanf())进行用户输入。 scanf() 在错误处理/恢复方面相当糟糕,而且管理空白也很尴尬。您的直接问题是 scanf(" %c", &chr); 之后仍在输入缓冲区中。
  • 我认为这是 scanf 被跳过的问题。请看这个答案。 stackoverflow.com/a/29775377/5774004
  • @SreeraghAR 我认为这似乎是问题所在,我所要做的就是在“%c”中添加空间。非常感谢!!!!

标签: c loops


【解决方案1】:

从标准输入流中读取类型假定您确切知道流中的下一个内容。正如 Streeragh 所提到的,您可能将换行符作为下一个输入字符。您可以通过转储 chr 来对它进行分类(尝试以十六进制表示,例如 %0x)。提到的文章也提供了很好的建议:将文本输入为 %s(或使用 readline),然后解析输入。查看strtok。还要注意标准输入可以从管道重定向(即 out.exe

【讨论】:

    猜你喜欢
    • 2016-01-19
    • 1970-01-01
    • 2014-04-12
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 2011-01-01
    相关资源
    最近更新 更多