简体   繁体   中英

How would I fix this if statement in C to get it working as intended?

In this piece of code for a "contact management system" I am having difficulty in getting the intended output for a line. Basically, during this one part when you are adding a new contact, it asks you to "please enter an apartment #" as shown below:

 if (yes() == 1)
 {
     printf("Please enter the contact's apartment number: ");
     address->apartmentNumber = getInt();
     if (address->apartmentNumber > 0)
     {
     }
     else
     {
        printf("*** INVALID INTEGER *** <Please enter an integer>: ");
        address->apartmentNumber = getInt();
    }
  }
  else
  {
      address->apartmentNumber = 0;
  }

Now, according to my assignment, you're supposed to enter the word (instead of a number, get it?) "bison" which brings up the output:

* INVALID INTEGER * Please enter an integer:

For context, this part works absolutely fine. However, you're then directed to put in the integer "-1200" which should then bring up the prompt

* INVALID APARTMENT NUMBER * Please enter a positive number:

It is this part that I'm having issue in because simply put, I don't know where to put it, whether in the if statement or outside of it. Im not sure, and would kindly like some help with this.

I have attempted to correct the problem my self, but it just gives me double of the Invalid integer output instead of this correct Invalid apartment number statement. Here is my (failed) attempt:

    if (yes() == 1)
    {
        printf("Please enter the contact's apartment number: ");
        address->apartmentNumber = getInt();

        if (address->apartmentNumber > 0)
        {
        }
        else
        {
            printf("*** INVALID INTEGER *** <Please enter an integer>: ");
            address->apartmentNumber = getInt();
        }
        if (address->apartmentNumber < 0)
        {
        }
        else
        {
            printf("*** INVALID APARTMENT NUMBER *** <Please enter a positive number>: ");
            address->apartmentNumber = getInt();       
        }
        else
        {
            address->apartmentNumber = 0;
        }

EDIT: For those who've asked for the code for getInt() and yes(), Here:

getInt()

int getInt(void)
{
    int num;
    char nl;

    scanf("%d%c", &num, &nl);
    while (nl != '\n') {
        clearKeyboard();

        printf("*** INVALID INTEGER *** <Please enter an integer>: ");
        scanf("%d%c", &num, &nl);
    }
    return num;
}

and yes():

int yes(void)
{
    int yesno, flag;
    char c, nl;
    scanf("%c%c", &c, &nl);

    do {
        if (nl != '\n') {
            clearKeyboard();

            printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
            flag = 1;
            scanf("%c%c", &c, &nl);
        }
        else if (c != 'Y' && c != 'y' && c != 'N' && c != 'n') {
            printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
            flag = 1;
            scanf("%c%c", &c, &nl);
        }
        else if (nl == '\n' && (c == 'Y' || c == 'y' || c == 'N' || c == 'n')) 
        {
            flag = 0;
        }
    } while (flag == 1);

    if (c == 'Y' || c == 'y') {
        yesno = 1;
    }
    else {
        yesno = 0;
    }
    return yesno;
}

getInt will take care of non-integer (text and words) input and will reprompt the user to type an integer until he does.

So your code needs to be more like this:

if (yes() == 1)
{
     int validNumber = 0;
     while (validNumber == 0)
     {
         printf("Please enter the contact's apartment number: ");
         address->apartmentNumber = getInt();
         if (address->apartmentNumber > 0)
         {
             validNumber = 1;
         }
         else
         {
             printf("* INVALID APARTMENT NUMBER * Please enter a positive number:\n");
         }
     }
}

Your getint() function is horribly fragile. What is to say the user enters a non-integer value only once? When taking input of a specific type, it is generally better to loop continually until you receive valid input (or the user cancels input), and always protect against the of the input not being what you expect (like when a cat steps on the keyboard...)

scanf can be used, if used correctly. This means you are responsible for checking the return of scanf every time . You must handle three conditions

  1. (return == EOF) the user canceled input by generating a manual EOF by pressing Ctrl+d (or on windows Ctrl+z , but see CTRL+Z does not generate EOF in Windows 10 (early versions) );
  2. (return < expected No. of conversions) a matching or input failure occurred. For a matching failure you must account for every character left in your input buffer. (scan forward in the input buffer reading and discarding characters until a '\\n' or EOF is found); and finally
  3. (return == expected No. of conversions) indicating a successful read -- it is then up to you to check whether the input meets any additional criteria (eg positive integer, positive floating-point, within a needed range, etc..).

Putting that to work with your getint() function and passing a character string to be displayed as a user prompt (if not NULL ), you could do something similar to:

int getint (int *value, const char *prompt)
{
    /* loop continually until good input or canceled */
    for (;;) {
        int rtn;        /* variable for return from scanf */
        if (prompt)                     /* if not NULL    */
            fputs (prompt, stdout);     /* display prompt */
        rtn = scanf ("%d", value);      /* attempt read   */

        if (rtn == EOF) {   /* check for manual EOF */
            fputs ("<user canceled input>\n", stderr);
            return 0;
        }
        empty_stdin();  /* all other cases - empty input buffer */
        if (rtn == 1)   /* good input, break */
            break;
        /* otherwise matching failure */
        fputs ("  error: invalid integer input.\n", stderr);
    }
    return *value;  /* value also available through pointer */
}

( note: the value returned from the function is the validation for whether the function succeeded (a return of 1 ) or whether the user canceled with EOF (a return of 0 ), the integer value is made available to the caller through the pointer value )

The helper function empty_stdin() is simply:

void empty_stdin (void)
{
    int c = getchar();
    while (c != '\n' && c != EOF)
        c = getchar();
}

There are many ways to put getint() together to tailor it to your needs, as long as you proper handle all three cases above, you are free to do it any way you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM