Dawid Gąbka
Dawid Gąbka

Reputation: 13

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;
    }

}

Upvotes: 0

Views: 183

Answers (2)

Mike C. Delorme
Mike C. Delorme

Reputation: 86

It looks like you allocated a as an array of character pointers (i.e. 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';

Upvotes: 3

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36391

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

Upvotes: 1

Related Questions