How to give a print statement error when the user inputs an invalid number's or letter in C

时间:2016-03-31 15:23:43

标签: c input menu

I have a while loop menu system that gathers the users inputs. However there are obviously a limited number of options to choose from (in this instance 4 and 6).

Menu One:

The first menu I have uses letters that the user inputs to select the action. I want the user to get a printf statement saying that they have entered an invalid letter if they use any of the letters that aren't used on the menu. This is the code below:

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);

My current error handle I use at the moment is:

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

This obviously doesn't work because if it isn't E for example but is still C it will still pull up the error message. I have since removed this.

My while loop uses this at the moment however it doesn't do anything and I am still very novice on how while loops work in C.

My question for this menu is how do I pull up a print statement error for this menu?

Menu Two:

The other menu I have is a bit more complicated as it uses a number system. It is basically like the menu above but rather just with numbers. However there are more conditions. The menu code is:

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

As shown there are a fair more conditions. I have tried many ways of trying to catch the error however the program would always crash or would show the print statement even if the condition isn't met.

I have tried !isdigit() however it would still play the statement even if it was a digit.

How do I catch these errors?

I am fairly new to C and their is limit sources on C online, hope you can help. Thanks in advance

Here is the whole code I have written if this isn't enough information:

Includes:

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

Calculations:

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;
}

Main:

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;

}

2 个答案:

答案 0 :(得分:2)

如果我是你,我可以使用下面的小功能验证菜单二的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。

并且您可以通过这种方式在代码中使用sub-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循环将运行并提示用户输入新输入,直到它成为有效输入, 同样,您可以验证输入的重置。

注意:在您的文件中添加#Include&lt; stdbool &gt; 标题。

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

你应该考虑使用Roux帖子来为Menu One选择使用switch语句。

答案 1 :(得分:1)

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

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

或者,除了Q,T,C和E之外,if(menuChoice != 'Q' && menuChoice != 'T' && menuChoice != 'C' && menuChoice != 'E')应为“true”。