Comparing user-inputted characters in C

前端 未结 4 1581
失恋的感觉
失恋的感觉 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: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') {
    

提交回复
热议问题