简体   繁体   English

我该如何解决用C语言编写的if语句,以使其按预期工作?

[英]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: 现在,根据我的任务,您应该输入单词“ bison”(而不是数字,得到它?),该单词将显示输出:

* INVALID INTEGER * Please enter an integer: * INVALID 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 但是,您将被指示输入整数“ -1200”,然后将弹出提示

* 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. 这是我遇到的问题,因为简单地说,无论是在if语句中还是在if语句之外,我都不知道将其放在哪里。 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()和yes()代码的人,这里:

getInt() 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. getInt将处理非整数(文本和单词)输入,并提示用户键入整数,直到输入为止。

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. 您的getint()函数非常脆弱。 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. 如果正确使用,可以使用scanf This means you are responsible for checking the return of scanf every time . 这意味着有责任每次都检查scanf返回 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) ); (return == EOF)用户通过按Ctrl + d生成手动EOF (或在Windows Ctrl + z上 ,但请参见CTRL + Z在Windows 10(早期版本)中不会生成 (return == EOF)来取消输入;
  2. (return < expected No. of conversions) a matching or input failure occurred. (return < expected No. of conversions)发生匹配输入失败。 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); (向前扫描输入缓冲区,读取并丢弃字符,直到找到'\\n'EOF ); 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..). (return == expected No. of conversions)表示读取成功-然后由您检查输入是否满足任何其他条件(例如,正整数,正浮点,在所需范围内等)。 。

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: 将其与getint()函数一起使用并传递一个字符串以显示为用户提示(如果不是NULL ),则可以执行以下操作:

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 ) 注意:从函数返回的值是对函数是否成功(返回1 )或用户是否通过EOF取消(返回0 )的验证,整数值可通过指针value提供给调用方)

The helper function empty_stdin() is simply: 辅助函数empty_stdin()简单来说就是:

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. 有多种方法可以将getint()放在一起以根据需要进行调整,只要您能正确处理上述所有三种情况,就可以随意使用任意方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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