【问题标题】:How to give a print statement error when the user inputs an invalid number's or letter in C当用户在 C 中输入无效数字或字母时如何给出打印语句错误
【发布时间】:2016-04-01 04:32:32
【问题描述】:

我有一个收集用户输入的 while 循环菜单系统。但是,显然可供选择的选项数量有限(在本例中为 4 和 6)。

菜单一:

我的第一个菜单使用用户输入的字母来选择操作。我希望用户得到一个 printf 语句,说明如果他们使用菜单上未使用的任何字母,他们输入了无效字母。这是下面的代码:

printf("\n\nOption | Action\n");
    printf("     Q | Quit\n");
    printf("     T | Loan Table\n");
    printf("     C | Calculate Loan\n");
    printf("     E | Explanation\n");
    printf("Select Option: ");
    fseek(stdin, 0, SEEK_END);
    scanf("%c", &menuChoice);
    menuChoice = toupper(menuChoice);

我目前使用的错误句柄是:

if(menuChoice != 'Q' || menuChoice != 'T' || menuChoice != 'C'  || menuChoice != 'E') 
    { 
    printf("Error! Choose a valid menu option.");        
    }

这显然是行不通的,因为如果它不是 E,例如,但仍然是 C,它仍然会拉出错误消息。我已经删除了这个。

我的 while 循环目前使用它,但它没有做任何事情,而且我对 while 循环在 C 中的工作方式仍然非常陌生。

我对这个菜单的问题是如何为这个菜单提取一个打印语句错误?

菜单二:

我的另一个菜单有点复杂,因为它使用数字系统。它基本上就像上面的菜单,但只是带有数字。但是还有更多的条件。菜单代码为:

printf("\nYou selected option C.\n");
        printf("\nLoan Calculator\n");
        printf("Option | Plan\n");
        printf("     1 | LF1\n");
        printf("     2 | LF2\n");
        printf("     3 | BBPL\n");
        printf("     4 | ILZERO\n");
        printf("     5 | ILFIVE\n");
        printf("     6 | LS5\n");
        printf("Select Plan: ");
        fseek(stdin, 0, SEEK_END);
        scanf("%d", &planCode);
        //CHECK IF IT IS A NUMBER BETWEEN 1 AND 6
        printf("Cost of car: ");
        fseek(stdin, 0, SEEK_END);
        scanf("%d", &carCost);
        //CHECK IF IT IS A NUMBER
        printf("Deposit: ");
        fseek(stdin, 0, SEEK_END);
        scanf("%d", &deposit);
        //CHECK IF IT IS A NUMBER
        printf("Length of Loan (years): ");
        fseek(stdin, 0, SEEK_END);
        scanf("%d", &loanLength);
        //CHECK IF IT IS A NUMBER AND IS BETWEEN 1 AND 10

如图所示,还有更多条件。我尝试了多种方法来尝试捕获错误,但是即使不满足条件,程序也会始终崩溃或显示打印语句。

我尝试过!isdigit(),但即使是数字,它仍然会播放该语句。

如何发现这些错误?

我是 C 的新手,他们的 C 在线资源有限,希望你能提供帮助。提前致谢

如果信息不足,这是我编写的全部代码:

包括:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>

计算:

double calcPayment(double loanAnnualRate, double loan, int length)
{
    double retv;
    int payments;
    double mul;
    double rate;
    rate = loanAnnualRate / 12;
    payments = length * 12;
    mul = pow(1 + rate, payments);
    retv = (loan * mul * rate) / (mul - 1);
    return retv;
}

主要:

int main()
{
    char menuChoice;
    int planCode;
    int carCost, deposit, loanLength;
    double loanInitial;
    double loanPayments;
    double IALSpecialRate;
    double fee;
    do
    {
        printf("\n\nOption | Action\n");
        printf("     Q | Quit\n");
        printf("     T | Loan Table\n");
        printf("     C | Calculate Loan\n");
        printf("     E | Explanation\n");
        printf("Select Option: ");
        fseek(stdin, 0, SEEK_END);
        scanf("%c", &menuChoice);
        menuChoice = toupper(menuChoice);

        if (menuChoice == 'T')
        {
            printf("\nYou selected option T.\n");
            printf("\nVendor Loan Details List\n");
            printf("+-----------------------------------------------------------------------------------------------------------------------+\n");
            printf("|   | Loan Vendor | Loan Product Code | Initial Fee | Monthly Fee | Interest Rate % | Max. Loan Amount | Min. Loan Amount |\n");
            printf("+-----------------------------------------------------------------------------------------------------------------------+\n");
            printf("| 1 | Leaf-Friend | LF1               | $150        | $0          | 6.14%%         | $70,000          | $5,000           |\n");
            printf("+-----------------------------------------------------------------------------------------------------------------------+\n");
            printf("| 2 | Leaf-Friend | LF2               | $155        | $0          | 6.24%%         | $70,000          | $1,000           |\n");
            printf("+-----------------------------------------------------------------------------------------------------------------------+\n");
            printf("| 3 | Big Bank    | BBPL              | $150        | $0          | 6.30%%         | $80,000          | $5,000           |\n");
            printf("+-----------------------------------------------------------------------------------------------------------------------+\n");
            printf("| 4 | ITSALOAN    | ILZERO            | $149        | $0          | 7.10%%*        | $50,000          | $1,000           |\n");
            printf("+-----------------------------------------------------------------------------------------------------------------------+\n");
            printf("| 5 | ITSALOAN    | ILFIVE            | $140        | $5          | 7.10%%*        | $50,000          | $1,000           |\n");
            printf("+-----------------------------------------------------------------------------------------------------------------------+\n");
            printf("| 6 | Loan Sheep  | LS5               | $349        | $0          | 5.91%%         | $50,000          | $500             |\n");
            printf("+-----------------------------------------------------------------------------------------------------------------------+\n");
            printf("NOTE*: ITSALOAN has a special promotion on at the moment for any loan above $20000 the interest rate drops to 6.1%");
        }
        if (menuChoice == 'C')
        {
            printf("\nYou selected option C.\n");
            printf("\nLoan Calculator\n");
            printf("Option | Plan\n");
            printf("     1 | LF1\n");
            printf("     2 | LF2\n");
            printf("     3 | BBPL\n");
            printf("     4 | ILZERO\n");
            printf("     5 | ILFIVE\n");
            printf("     6 | LS5\n");
            printf("Select Plan: ");
            fseek(stdin, 0, SEEK_END);
            scanf("%d", &planCode);
            //CHECK IF IT IS A NUMBER BETWEEN 1 AND 6
            printf("Cost of car: ");
            fseek(stdin, 0, SEEK_END);
            scanf("%d", &carCost);
            //CHECK IF IT IS A NUMBER
            printf("Deposit: ");
            fseek(stdin, 0, SEEK_END);
            scanf("%d", &deposit);
            //CHECK IF IT IS A NUMBER
            printf("Length of Loan (years): ");
            fseek(stdin, 0, SEEK_END);
            scanf("%d", &loanLength);
        //CHECK IF IT IS A NUMBER AND IS BETWEEN 1 AND 10
        if (planCode == 1)
        {
            loanInitial = carCost - deposit;

            if (loanInitial < 5000.00)
            {
                printf("\nSorry! Your loan is too low to be used with LF1.\nTry either LF2, ILZERO or ILFIVE.\n");
            }
            if (loanInitial > 70000.00)
            {
                printf("\nSorry! Youe loan is too high to be used with LF1.\nTry BBPL.\n");
            }
            if (loanInitial >= 5000.00 && loanInitial <= 70000.00)
            {
                loanPayments = calcPayment(0.0614, loanInitial, loanLength);
                fee = 150;

                printf("Loan Size                    : $ %8.2lf", loanInitial);
                printf("\nTotal Repayment              : $ %8.2lf", loanPayments * 12 * loanLength + fee);
                printf("\nMonthly Repayments           : $ %8.2lf", loanPayments);
                printf("\nAnnual Repayment(s)          : $ %8.2lf", loanPayments * 12);
                printf("\nTotal Repayment Without Fees : $ %8.2lf", loanPayments * 12 * loanLength);
                printf("\nTotal Fees                   : $ %8.2lf", fee);
                printf("\nActual Loan Cost             : $ %8.2lf", loanPayments * 12 * loanLength + fee - loanInitial);
            }
        }
        if (planCode == 2)
        {
            loanInitial = carCost - deposit;

            if (loanInitial < 5000.00)
            {
                printf("\nSorry! Your loan is too low to be used with LF2.\nTry LS5\n");
            }
            if (loanInitial > 70000.00)
            {
                printf("\nSorry! Youe loan is too high to be used with LF2.\nTry BBPL.\n");
            }
            if (loanInitial >= 1000.00 && loanInitial <= 70000.00)
            {
                loanPayments = calcPayment(0.0624, loanInitial, loanLength);
                fee = 155;

                printf("Loan Size                     : $ %8.2lf", loanInitial);
                printf("\nTotal Repayment               : $ %8.2lf", loanPayments * 12 * loanLength + fee);
                printf("\nMonthly Repayments            : $ %8.2lf", loanPayments);
                printf("\nAnnual Repayment(s)           : $ %8.2lf", loanPayments * 12);
                printf("\nTotal Repayment Without Fees  : $ %8.2lf", loanPayments * 12 * loanLength);
                printf("\nTotal Fees                    : $ %8.2lf", fee);
                printf("\nActual Loan Cost              : $ %8.2lf", loanPayments * 12 * loanLength + fee - loanInitial);
            }
        }
        if (planCode == 3)
        {
            loanInitial = carCost - deposit;

            if (loanInitial < 5000.00)
            {
                printf("\nSorry! Your loan is too low to be used with BBPL.\nTry either LF2, ILZERO or ILFIVE.\n");
            }
            if (loanInitial > 80000.00)
            {
                printf("\nSorry! Youe loan is too high to be used with BBPL.\nTry a cheaper car below $80,000.\n");
            }
            if (loanInitial >= 5000.00 && loanInitial <= 80000.00)
            {
                loanPayments = calcPayment(0.063, loanInitial, loanLength);
                fee = 150;

                printf("Loan Size                    : $ %8.2lf", loanInitial);
                printf("\nTotal Repayment              : $ %8.2lf", loanPayments * 12 * loanLength + fee);
                printf("\nMonthly Repayments           : $ %8.2lf", loanPayments);
                printf("\nAnnual Repayment(s)          : $ %8.2lf", loanPayments * 12);
                printf("\nTotal Repayment Without Fees : $ %8.2lf", loanPayments * 12 * loanLength);
                printf("\nTotal Fees                   : $ %8.2lf", fee);
                printf("\nActual Loan Cost             : $ %8.2lf", loanPayments * 12 * loanLength + fee - loanInitial);
            }
        }
        if (planCode == 4)
        {
            loanInitial = carCost - deposit;

            if (loanInitial < 1000.00)
            {
                printf("\nSorry! Your loan is too low to be used with ILFIVE.\nTry LS5.\n");
            }
            if (loanInitial > 50000.00)
            {
                printf("\nSorry! Youe loan is too high to be used with ILFIVE.\nTry either LF1, LF2, BBPL or LS5.\n");
            }
            if (loanInitial >= 1000.00 && loanInitial <= 50000.00)
            {
                if (loanInitial >= 20000) { IALSpecialRate = 0.061; }
                else IALSpecialRate = 0.071;
                loanPayments = calcPayment(IALSpecialRate, loanInitial, loanLength);
                fee = 149;

                printf("Loan Size                    : $ %8.2lf", loanInitial);
                printf("\nTotal Repayment              : $ %8.2lf", loanPayments * 12 * loanLength + fee);
                printf("\nMonthly Repayments           : $ %8.2lf", loanPayments);
                printf("\nAnnual Repayment(s)          : $ %8.2lf", loanPayments * 12);
                printf("\nTotal Repayment Without Fees : $ %8.2lf", loanPayments * 12 * loanLength);
                printf("\nTotal Fees                   : $ %8.2lf", fee);
                printf("\nActual Loan Cost             : $ %8.2lf", loanPayments * 12 * loanLength + fee - loanInitial);
            }
        }
        if (planCode == 5)
        {
            loanInitial = carCost - deposit;

            if (loanInitial < 1000.00)
            {
                printf("\nSorry! Your loan is too low to be used with ILFIVE.\nTry LS5.\n");
            }
            if (loanInitial > 50000.00)
            {
                printf("\nSorry! Youe loan is too high to be used with ILFIVE.\nTry either LF1, LF2, BBPL or LS5.\n");
            }
            if (loanInitial >= 1000.00 && loanInitial <= 50000.00)
            {

                if (loanInitial >= 20000) { IALSpecialRate = 0.061; }
                else IALSpecialRate = 0.071;

                loanPayments = calcPayment(IALSpecialRate, loanInitial, loanLength);
                loanPayments = calcPayment(0.071, loanInitial, loanLength);
                fee = 40;

                printf("Loan Size                    : $ %8.2lf", loanInitial);
                printf("\nTotal Repayment              : $ %8.2lf", loanPayments * 12 * loanLength + fee + (60 * loanLength));
                printf("\nMonthly Repayments           : $ %8.2lf", loanPayments + 5);
                printf("\nAnnual Repayment(s)          : $ %8.2lf", loanPayments * 12 + 60);
                printf("\nTotal Repayment Without Fees : $ %8.2lf", loanPayments * 12 * loanLength);
                printf("\nTotal Fees                   : $ %8.2lf", fee);
                printf("\nActual Loan Cost             : $ %8.2lf", loanPayments * 12 * loanLength + fee - loanInitial + (60 * loanLength));
            }
        }
        if (planCode == 6)
        {
            loanInitial = carCost - deposit;

            if (loanInitial < 500.00)
            {
                printf("\nSorry! Your loan is too low to be used with LS5.\n");
            }
            if (loanInitial > 55000.00)
            {
                printf("\nSorry! Youe loan is too high to be used with LS5.\nTry either LF1, Lf2 or BBPL.\n");
            }
            if (loanInitial >= 500.00 && loanInitial <= 55000.00)
            {
                loanPayments = calcPayment(0.0591, loanInitial, loanLength);
                fee = 349;

                printf("Loan Size                    : $ %8.2lf", loanInitial);
                printf("\nTotal Repayment              : $ %8.2lf", loanPayments * 12 * loanLength + fee);
                printf("\nMonthly Repayments           : $ %8.2lf", loanPayments);
                printf("\nAnnual Repayment(s)          : $ %8.2lf", loanPayments * 12);
                printf("\nTotal Repayment Without Fees : $ %8.2lf", loanPayments * 12 * loanLength);
                printf("\nTotal Fees                   : $ %8.2lf", fee);
                printf("\nActual Loan Cost             : $ %8.2lf", loanPayments * 12 * loanLength + fee - loanInitial);
            }
        }
    }
    if (menuChoice == 'E') { printf("\nYou selected option E.\n"); }
    if (menuChoice == 'Q')
    {
        printf("\nExiting Program...\n");
        exit(0);
    }
} while (menuChoice != 'Q' || menuChoice != 'T' || menuChoice != 'C' || menuChoice != 'E');
printf("\nPlease Choose a valid option.\n"); 

_getch;
return 0;

}

【问题讨论】:

  • if(menuChoice != 'Q' || menuChoice != 'T' || menuChoice != 'C' || menuChoice != 'E') 将永远为真。想一想。你会意识到你需要&amp;&amp;,而不是||
  • 我知道。你没看我的问题吗? “这显然是行不通的,因为如果它不是 E,但仍然是 C,它仍然会拉出错误消息。我已经删除了这个。”
  • @Cool Guy 实际上是对的。如果字符不是指定的字符,您想打印错误 - 也就是说,如果它不是 Q AND 不是 T AND ...但是 Roux 提供的switch 解决方案更好。
  • @HonzaRemeš 我试过了,但是无论条件如何,我都会显示错误消息。即使我使用有效的 Letter,它仍然会显示错误消息。
  • 第1步:scanf("%c", &amp;menuChoice); --> scanf(" %c", &amp;menuChoice);(加空格)..第2步:不要使用scanf(),移动到fgets()

标签: c input menu


【解决方案1】:

如果我是你,我可以使用下面的小功能验证菜单二的 scanf 输入:

bool readAndValidateInput(int* input, int min, int max) {
fseek(stdin, 0, SEEK_END);
if (scanf(" %d", input) != 1) {
    fprintf(stderr, "Invalid input.\n");
    return false;
}

if (min == 0 && max == 0)
    return true;

if (*input < min || *input > max) {
    fprintf(stderr, "Input not in range.\n");
    return false;
}

return true; }

第一个参数是存储输入值的指针,第二个和第三个参数是检查输入的范围。 如果你不想检查范围,你可以提供 0 到 min 和 max。

您可以通过这种方式在代码中将它与子 do-while 循环一起使用:

        do {
           printf("Select Plan: ");
           //CHECK IF IT IS A NUMBER BETWEEN 1 AND 6
        } while (!readAndValidateInput(&planCode, 1, 6))

        do {
            printf("Cost of car: ");
            // supply 0 for min and max to omit range validation
        } while(!readAndValidateInput(&carCost, 0, 0));

Do-While 循环将运行并提示用户输入新输入,直到输入有效为止, 同样的方式你可以验证输入的重置。

注意:在您的文件中也添加 #Includestdbool> 标头。

您可能还需要阅读此Link 中有关 SCANF(...) 及其返回值含义的信息。

并且您应该考虑将 Roux 发布为菜单一选项使用 switch 语句。

【讨论】:

  • 哇。太感谢了。它很容易实现并且效果很好。有一些语法错误,例如缺少 ';'但除此之外。太棒了。
【解决方案2】:

试试swich 声明,也许?它允许您为“菜单选择”的某些值选择操作,并为“所有其他值”选择操作。这是一个例子:

switch (menuChoice)
{ 
  case 'Q': 
    do_whatever_q_does();
    break; 
  case 'E': 
    do_whatever_e_does();
    break;
  (and so on)
  default :
    throw_error_message();
}

或者,if(menuChoice != 'Q' &amp;&amp; menuChoice != 'T' &amp;&amp; menuChoice != 'C' &amp;&amp; menuChoice != 'E') 对于除 Q、T、C 和 E 之外的任何内容都应为“真”。

【讨论】:

  • 您应该考虑如果用户键入多个字符会发生什么。例如,“QT”。应该发生什么?当前的代码会接受这个作为答案“Q”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 2022-12-05
相关资源
最近更新 更多