If statement runs through whether conditions are met or not

后端 未结 4 1209
北海茫月
北海茫月 2021-01-28 17:13

My if statement runs through as if the conditions have been met even when they haven\'t. I have tried moving bits of code about and even rewriting the if statement differently b

相关标签:
4条回答
  • 2021-01-28 17:25

    This is really bogus

    if (bob == "no", "No", "NO", "nO")
    

    You need to break it out with logical OR instead

    if (bob == "no" || bob == "No" || bob == "NO" || bob == "nO")
    

    As it stand, this if (bob == "no", "No", "NO", "nO") would be equivalent to if("nO") as the effect of the comma operator.

    0 讨论(0)
  • 2021-01-28 17:26
    bob == "no", "No", "NO", "nO"
    

    is not doing what you think it is doing. You mean to do:

    bob == "no" ||
    bob == "No" ||
    bob == "NO" ||
    bob == "nO"
    
    0 讨论(0)
  • 2021-01-28 17:36

    This is a bit of a side note to your question, but in this context, you may want to consider converting the answer to lowercase (or uppercase) before comparing it.

    That way, you can just use if (tolower(bob) == "no")


    Here's an example of how to do use the tolower function

    http://www.cplusplus.com/reference/cctype/tolower/

    /* tolower example */
    #include <stdio.h>
    #include <ctype.h>
    int main ()
    {
      int i=0;
      char str[]="Test String.\n";
      char c;
      while (str[i])
      {
        c=str[i];
        putchar (tolower(c));
        i++;
      }
      return 0;
    }
    
    0 讨论(0)
  • 2021-01-28 17:40

    Your loop problem can be explained:

    while (continueBool = true)

    should read

    while (continueBool == true).

    As your code currently stands, you are setting it to true instead of checking for a value, so it will never exit.

    0 讨论(0)
提交回复
热议问题