Comparing user-inputted characters in C

前端 未结 4 1556
失恋的感觉
失恋的感觉 2020-12-30 04:47

The following code snippets are from a C program.

The user enters Y or N.

char *answer = \'\\0\';

scanf (\" %c\", answer);

if (*answer == (\'Y\' ||         


        
相关标签:
4条回答
  • 2020-12-30 05:01

    Because comparison doesn't work that way. 'Y' || 'y' is a logical-or operator; it returns 1 (true) if either of its arguments is true. Since 'Y' and 'y' are both true, you're comparing *answer with 1.

    What you want is if(*answer == 'Y' || *answer == 'y') or perhaps:

    switch (*answer) {
      case 'Y':
      case 'y':
        /* Code for Y */
        break;
      default:
        /* Code for anything else */
    }
    
    0 讨论(0)
  • 2020-12-30 05:08

    I see two problems:

    The pointer answer is a null pointer and you are trying to dereference it in scanf, this leads to undefined behavior.

    You don't need a char pointer here. You can just use a char variable as:

    char answer;
    scanf(" %c",&answer);
    

    Next to see if the read character is 'y' or 'Y' you should do:

    if( answer == 'y' || answer == 'Y') {
      // user entered y or Y.
    }
    

    If you really need to use a char pointer you can do something like:

    char var;
    char *answer = &var; // make answer point to char variable var.
    scanf (" %c", answer);
    if( *answer == 'y' || *answer == 'Y') {
    
    0 讨论(0)
  • 2020-12-30 05:10

    For a start, your answer variable should be of type char, not char*.

    As for the if statement:

    if (answer == ('Y' || 'y'))
    

    This is first evaluating 'Y' || 'y' which, in Boolean logic (and for ASCII) is true since both of them are "true" (non-zero). In other words, you'd only get the if statement to fire if you'd somehow entered CTRLA (again, for ASCII, and where a true values equates to 1)*a.

    You could use the more correct:

    if ((answer == 'Y') || (answer == 'y'))
    

    but you really should be using:

    if (toupper(answer) == 'Y')
    

    since that's the more portable way to achieve the same end.


    *a You may be wondering why I'm putting in all sorts of conditionals for my statements. While the vast majority of C implementations use ASCII and certain known values, it's not necessarily mandated by the ISO standards. I know for a fact that at least one compiler still uses EBCDIC so I don't like making unwarranted assumptions.

    0 讨论(0)
  • 2020-12-30 05:15

    answer shouldn't be a pointer, the intent is obviously to hold a character. scanf takes the address of this character, so it should be called as

    char answer;
    scanf(" %c", &answer);
    

    Next, your "or" statement is formed incorrectly.

    if (answer == 'Y' || answer == 'y')
    

    What you wrote originally asks to compare answer with the result of 'Y' || 'y', which I'm guessing isn't quite what you wanted to do.

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