【问题标题】:How to make this program ask for input again if invalid input is entered (in C programming)? [duplicate]如果输入无效输入(在 C 编程中),如何使该程序再次要求输入? [复制]
【发布时间】:2017-07-16 19:23:57
【问题描述】:

检查发生在两个不同的位置。

也就是说,在您输入asmdq 的位置以及输入第一个和第二个数字时。

在任何检查中,如果检查为假,它应该要求您重新输入您的输入。

我猜这可以通过在 while 循环检查中放置数字部分的 scanf 语句来完成,但是当我输入无效值(非数字)时,循环会无限运行。

所以我一定做错了什么。我已经使asmdq 部分大部分工作。

但第二部分似乎永远不会奏效。为此,我将失败的尝试留在了 while 循环中,而不是 //comments

任何帮助将不胜感激! 到目前为止,这是我的代码:

#include <stdio.h>
#include <ctype.h>

int main(void)
{
    char ch;
    float num1,num2,answer;
    printf("Enter the operation of your choice:\n");
    printf("a. add      s. subtract\n");
    printf("m. multiply q. divide\n");
    printf("q. quit\n");
    while ((ch = getchar())!='q')
    {
        printf("Enter the operation of your choice:\n");
        printf("a. add      s. subtract\n");
        printf("m. multiply q. divide\n");
        printf("q. quit\n");
        ch=tolower(ch);
        if (ch=='\n')
            continue;
        else
        {
            switch(ch)
            {
                case 'a':
                //The code below is what I have tried to make work.
                //This code would also be copy pasted to the other cases,
                //of course with the correct operations respectively being used.
                //
                //printf("Enter first number: ")
                //while(scanf("%f",&num1)==0)
                //{
                //  printf("Invalid input. Please enter a number.");
                //  scanf("%f",&num1);
                //}
                //printf("Enter second number: ")
                //while(scanf("%f",&num2)==0)
                //{
                //  printf("Invalid input. Please enter a number.");
                //  scanf("%f",&num2);
                //}
                //answer = num1 + num2;
                //printf("%f + %f = %f\n",num1,num2,answer);
                //break;
                //
                //I have also tried to make this work using do-while loops
                printf("Enter first number: ");
                scanf("%f",&num1);
                printf("Enter second number: ");
                scanf("%f",&num2);
                answer = num1 + num2;
                printf("%f + %f = %f\n",num1,num2,answer);
                break;
            case 's':
                printf("Enter first number: ");
                scanf("%f",&num1);
                printf("Enter second number: ");
                scanf("%f",&num2);
                answer = num1 - num2;
                printf("%f - %f = %f\n",num1,num2,answer);
                break;
            case 'm':
                printf("Enter first number: ");
                scanf("%f",&num1);
                printf("Enter second number: ");
                scanf("%f",&num2);
                answer = num1 * num2;
                printf("%f * %f = %f\n",num1,num2,answer);
                break;
            case 'd':
                printf("Enter first number: ");
                scanf("%f",&num1);
                printf("Enter second number: ");
                scanf("%f",&num2);
                answer = num1 / num2;
                printf("%f / %f = %f\n",num1,num2,answer);
                break;
            default:
                printf("That is not a valid operation.\n");
                break;
        }
    }
}
return 0;
}

再次感谢您的帮助! 你会是一个救生员! 干杯! -Will S.

编辑:我的代码可以工作了!这是最终的代码...

#include <stdio.h>
#include <ctype.h>

int main(void)
{
    char ch;
    float num1,num2,answer;
    printf("Enter the operation of your choice:\n");
    printf("a. add      s. subtract\n");
    printf("m. multiply q. divide\n");
    printf("q. quit\n");
    while ((ch = getchar())!='q')
    {
        ch=tolower(ch);
        //Ignore whitespace
        if (ch=='\n')
            continue;
        else
        {
            switch(ch)
            {
                //Addition part
                case 'a':
                    //First number
                    printf("Enter first number: ");
                    //Check to see if input is a number
                while (scanf("%f",&num1)==0)
                {
                    printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
                    scanf("%*s");
                }
                //Second number
                printf("Enter second number: ");
                while (scanf("%f",&num2)==0)
                {
                    printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
                    scanf("%*s");
                }
                //Do math for respective operation
                answer = num1 + num2;
                //Print out result
                printf("%.3f + %.3f = %.3f\n", num1,num2,answer);
                break;
            //Subtraction part
            case 's':
                printf("Enter first number: ");
                while (scanf("%f",&num1)==0)
                {
                    printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
                    scanf("%*s");
                }
                printf("Enter second number: ");
                while (scanf("%f",&num2)==0)
                {
                    printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
                    scanf("%*s");
                }
                answer = num1 - num2;
                printf("%.3f - %.3f = %.3f\n", num1,num2,answer);
                break;
            //Multiplication part
            case 'm':
                printf("Enter first number: ");
                while (scanf("%f",&num1)==0)
                {
                    printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
                    scanf("%*s");
                }
                printf("Enter second number: ");
                while (scanf("%f",&num2)==0)
                {
                    printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
                    scanf("%*s");
                }
                answer = num1 * num2;
                printf("%.3f * %.3f = %.3f\n", num1,num2,answer);
                break;
            //Division part
            case 'd':
                printf("Enter first number: ");
                while (scanf("%f",&num1)==0)
                {
                    printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
                    scanf("%*s");
                }
                printf("Enter second number: ");
                while (scanf("%f",&num2)==0)
                {
                    printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
                    scanf("%*s");
                }
                //Check for if number is a zero
                while (num2==0)
                {
                    printf("Please enter a non-zero number, such as 2.5, -1.78E8, or 3: ");
                    while (scanf("%f",&num2)==0)
                    {
                        printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
                        scanf("%*s");
                    }
                }
                answer = num1 / num2;
                printf("%.3f / %.3f = %.3f\n", num1,num2,answer);
                break;
            //For if a non-valid operation is entered
            default:
                printf("That is not a valid operation.\n");
                break;
        }
    }
    printf("Enter the operation of your choice:\n");
    printf("a. add      s. subtract\n");
    printf("m. multiply q. divide\n");
    printf("q. quit\n");
}
printf("Bye.\n");
return 0;

}

回想起来,我可能可以不用 if/else 语句。

【问题讨论】:

  • 在你的 switch() 的每一种情况下,如果你检测到错误的输入,你可以简单地忽略输入,打印一个“输入被忽略,重新开始”,然后break。用户将不得不再次选择该操作。否则,你必须使用一个循环,或者一个带有循环的函数,里面有一个数字。
  • 函数:getchar() 返回 int,而不是 char。所以ch的声明不正确
  • 代码将多次输出菜单,因为用户要输入字符,他们还必须按 /enter/return/ 键 下一次调用 getchar() 检索'\n'钥匙。为了避免这种情况,清空stdin 流,类似于:while( (ch == getchar()) != EOF &amp;&amp; '\n' != ch );
  • 在调用任何scanf() 系列函数时,始终检查返回值(而不是参数值)以确保操作成功
  • 注意:对scanf()的调用也会在stdin流中留下'\n',所以需要在调用scanf()输入下一个动作之前消耗掉。

标签: c loops input while-loop scanf


【解决方案1】:

您的代码存在多个问题。首先在这个循环中

  1. 您在失败时接受了两次输入

    while(scanf("%f",&num1)==0)   //Taking Input Here Once
    {
        printf("Invalid input. Please enter a number.");
        scanf("%f",&num1);             //Again Taking input.
    }
    

    相反,您想要检查scanf() 的返回值,如果是0,您将再次执行循环,所以这是执行此操作的方法:

    int l = 0;
    
    while(l==0){  //Checking l, if it is zero or not, if zero running loop again.
        printf("Invalid input. Please enter a number.");
        l = scanf("%f",&num1);                   //Storing Return Value of scanf in l   
    }
    
  2. 当程序遇到任何带有scanf("%f" , &amp;num1)scanf("%f" , &amp;num2) 的行时,它将跳过所有空格并等待下一次输入。如果输入与格式规范不匹配,则输入不会被消耗并保留在输入缓冲区中。

    int l = 0;
    
    while(l==0){  //Checking l 
    
         printf("Invalid input. Please enter a number.");
         l = scanf("%f",&num1);  //scanf will look at the buffer if the input
                                 //does not match, it will not be consumed 
                                 //and will remain in buffer.       
    }
    

    换句话说,不匹配的字符永远不会被读取。所以当你输入例如a 字符,您的代码将无限循环,因为scanf 在同一字符上继续失败。

  3. 当程序执行其最后一次scanf("%f",&amp;num2) 调用时,由于 enter 缓冲区中存在换行符\n,因此由于ch = getchar(),换行符\n 得到存储在ch 和以下if 条件满足并再次执行循环。

     if(ch =='\n')
         continue;
    

【讨论】:

    【解决方案2】:
    while(scanf("%f",&num1)==0)
    {
         printf("Invalid input. Please enter a number.");
          scanf("%f",&num1);
     }
    

    这个循环每次迭代扫描两个数字。这不是你想要的。输了第二个scanf

    您还应该检查 EOF 和错误。

    int result;
    while((result = scanf("%f",&num1))==0)
    {
         printf("Invalid input. Please enter a number.");
    }
    
    if (result == EOF) .... report an error and exit ...
    

    【讨论】:

    • 我想确认的上述答案是否正确?
    • 事情是我自己是一个初学者,我每次只是确保我没有向 OP 提供任何错误、未定义或实施特定的信息。
    猜你喜欢
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多