简体   繁体   中英

Char comparison in C, if-statement

I'm having this problem with my code. The thing is I need to compare two chars n and a[p] but the result is always negative. This is a little quiz program for my assignment. q[] is an array of questions and a[] is an array of answers. The player enters t or f for true or false but the if doesn't seem to work as it always prints 'You lose!' (even if the condition is true).

char questions(){
const char *q [100];
q[0]= "Centipedes always have 100 feet."; //f
q[1] = "Marie Curie’s husband was called Pierre."; //t
[...]
q[99] = "";

const char *a[100];
a[0] = "f";
a[1] = "t";
[...]
a[99] = "";

char n;
int p, i;
for (i = 0; i<=7; ++i)
{
    srand(time(NULL));
    p = (rand() % 18);

    printf("\n");
    printf(q[p]);
    printf("\n");

    fflush(stdin);
    scanf("%c", &n);

    if (n == a[p]){
        printf("Correct answer!\n");
    }
    else
    {
        printf("You lose!");
        break;
    }

}

It looks like you allocated a as an array of character pointers (ie an array of c strings) instead of an array of characters:

const char *a[100];

Try allocating an array of characters instead of an array of character pointers and initialize your values as characters instead of c strings:

  • const char *a[100]; becomes char a[100]; - don't forget to drop the const since you write values to your array later on.

  • a[0] = "f"; becomes a[0] = 'f';

Your test is wrong. You are currently testing char against char * ...

Two ways to correct :

  1. declare a as an array of chars not char * . char a[100]; then initialize them with a[0]='f';
  2. or change your test to if (n==a[p][0]) so that you test n against the first char of the p-th string

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