-1

I am creating simple heads or tails game, however, I am trying to come up with a condition where if you insert "h" and the randomly generated answer is heads, the code prints that you get the answer correct. The randomly generated heads or tails is working fine, however, I do not know how to refer to the result of the flip, in the if condition at the end of my code.

Here's my code so far:

#include<stdio.h>
#include<unistd.h> //for sleep function
#include <stdlib.h> //for array
#include <time.h> //for random array

    //Array 
  int cool(void) {
    int i;
    int ht;

    i = 2;
    ht = 0;
    srand((unsigned)time(NULL));
    ht = rand() % i;
    return ht;
}

int main(int argc, char **argv)

And the second part

const char* o[2] = { 
     "Heads", "Tails"       //Where the words heads and tails are stored 
     };

//Coin Flip begins
    printf("\nType 'h' for heads & 't' for tails\n");
    printf("\nHeads or Tails? \n");
    scanf("%c", &a);
    //sleep(3);
    printf("%s\n",o[cool()]); //random heads or tails generated
    //sleep(3);


    if ( o == "Heads" && a == 'h' || o== "Heads" a == 'H' )
    {
        printf("\nCorrect!\n");

    }

    return 0;

}

Apologies if this has been asked before or I have asked incorrectly. I am new to coding and stack so feedback would be helpful

bobby-hg
  • 1
  • 1
  • 3
    `srand((unsigned)time(NULL));` is in the wrong place :please read up on it! – Weather Vane Mar 28 '18 at 10:57
  • 2
    If `o == "Heads"` doesn't make sense: `o` isn't a string (it is an array of strings) and, in any event, that isn't how you test strings for equality. – John Coleman Mar 28 '18 at 10:58
  • [srand() — why call it only once?](https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once). – Lundin Mar 28 '18 at 11:00
  • You need to store the results of `cool()` somewhere and then `o == "Heads" becomes `cool_result = 0` or something – Chris Turner Mar 28 '18 at 11:00
  • In the internal logic of the program just use `0` and `1` for `"Heads"` and `"Tails"`, reserving strings for input/output. Don't convert input `'h'` to `"Heads"` -- convert it to either 0 or 1 (depending on which one you want to represent heads). Something like `guess = a == 'h' ? 0 : 1`; will convert a 1-character input to either `0` or `1`. – John Coleman Mar 28 '18 at 11:07

1 Answers1

0

You must save the value returned by cool() in a variable, like:

int res = cool();
printf("%s\n",o[res]); //random heads or tails generated

then your if-statement can be something like:

if ((a == 'h' || a == 'H') && res == 0)

or

if (toupper(a) == 'H' && res == 0)

If you prefer to compare with strings, you can do it using strcmp like:

if ((a == 'h' || a == 'H') && (strcmp(o[res], "Heads") == 0))

Notice that strings can not be compared using ==

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63