-3

I need help finishing my program. I can't seem to get the last step, when the user enters 'y' to play another game it should start again. If the user enters 'n' then it should end. Thank you in advance for any help. Below is the code I have so far.

Here is the problem:
Write a C program that plays a number guessing game with the user.

Below is the sample run:

OK, I am thinking of a number. Try to guess it.

Your guess?  50
Too high!
Your guess?  250
Illegal guess. Your guess must be between 1 and 200.
Try again. Your guess? 30
**** CORRECT  ****
Want to play again?  y
Ok, I am thinking of a number. Try to guess it.
Your guess?  58
****  CORRECT  ***
Want to play again? n
Goodbye, It was fun. Play again soon.

Code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int i, number, currentGuess, MAX_GUESS = 5;
    int answer = 'n';
    time_t t;

    srand((unsigned) time(&t));
    number = rand() % 200 + 1;

    printf("Welcome to the game of Guess It! \nI will choose a number between 1 and 200. \nYou will try to guess that number.");
    printf("If you guess wrong, I will tell you if you guessed too high or too low. \nYou have 5 tries to get the number. \n");
    printf("\nOK, I am thinking of a number. Try to guess it. \n");

    for (i = 0; i < MAX_GUESS; i++) {
        printf("\nYour guess?");
        scanf("%i", &currentGuess);

        if (currentGuess > 200) {
            printf("Illegal guess. Your guess must be between 1 and 200.\n");
            printf("Try again.\n ");
        }
        else if (currentGuess > number) {
            printf("Too high!\n");
        }
        else if (currentGuess < number) {
            printf("Too low!\n");
        }
        else {
            printf("****CORRECT****\n");
            return 0;
        }
    }

    printf("Sorry you have entered the maximum number of tries. \n");
    printf("Want to play again? \n");
    scanf("%i", &answer);

    if(answer == 'n') {
        printf("Goodbye, it was fun. Play again soon.\n");
        return 0;
    }
    else if (answer != 'n') {
        printf("Ok, I am thinking of a number. Try to guess it.\n");
    }
}
Azeem
  • 11,148
  • 4
  • 27
  • 40
lizmart
  • 35
  • 1
  • 1
  • 5
  • Export your code to another method. int game(){....} and from main() just call game(). Then when you want the user to restart just call game() again – Pentarex Jun 25 '17 at 04:38
  • You should look at https://stackoverflow.com/questions/44742209/im-trying-to-code-a-number-guessing-game. It seems you're both trying to solve a similar coding problem. – Jonathan Leffler Jun 25 '17 at 04:54
  • And look at `man scanf` and think about `scanf("%i", &answer);` and `if(answer == 'n')`. Specifically what the problems may be. When you enter `n` for the answer, what does `scanf` think `n` is? – David C. Rankin Jun 25 '17 at 04:57
  • You may also want to see a surprisingly similar [**I'm trying to code a number guessing game**](https://stackoverflow.com/questions/44742209/im-trying-to-code-a-number-guessing-game) – David C. Rankin Jun 25 '17 at 05:03
  • Just kids with the same homework assignment. The last chump didn't even bother to reward those amazing answers. – cs95 Jun 25 '17 at 05:13
  • Thank you David! Many of us have the same problem since the book our teacher gave us doesn't do a good job of explaining it. If you have any book recommendations for beginners please let us know, we could really use it obviously. – lizmart Jun 25 '17 at 05:20

2 Answers2

0

Here's an idea for you to do this in your code:

char answer = 'y';

do
{
    // ...
    printf( "Want to play again (y/n)? " );
    scanf( " %c", &answer );
    // Mind ^ the space here to discard any
    // previously read newline character

} while ( answer == 'y' );
Azeem
  • 11,148
  • 4
  • 27
  • 40
  • Thank you Azeem, I will try it. – lizmart Jun 25 '17 at 05:21
  • 1
    ... umm, no. You need to check the return value of `scanf`. if the user presses Ctrl+D/Ctrl+Z, then `y` is assumed. Likewise, you're not discarding the extra whitespace in the answer, so if for example the newline is still unread, then it will be consumed by this, and you get the message twice... – Antti Haapala -- Слава Україні Jun 25 '17 at 06:39
  • @AnttiHaapala: Thanks! I've updated my answer about the newline suppression and left the return value check of `scanf` for the OP as an exercise. – Azeem Jun 25 '17 at 10:44
0

Check the below code, you might wanna understand the code, rather than just copy pasting it.

  1. The code delegates the task of doing a repetitive task to a function.

  2. The code then relies on the function to say how many chances player has played, or -1 for successful.

  3. And note the getchar() rather than scanf.

NOTE: The extra getchar() is needed, because I don't know but taking character input after taking integer input puts a '\n' character in the stdin, which results in unwanted behaviour. So this is a small trick I always use to tackle such cases.

  1. Pay attention to the do while loop, this case becomes a classic example where you should use do while loop.

  2. Also I have used macros to define MAX_GUESS. That's a good practice. You might wanna google it for "why?"

If you have any further queries, do comment in the answer.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>

#define MAX_GUESS 5

int playGame(int number)
{
    printf("\nOK, I am thinking of a number. Try to guess it. \n");

    int i, currentGuess;

    for (i=0; i<MAX_GUESS; i++){

        printf("\nYour guess?: ");
        scanf("%i", &currentGuess);

        if (currentGuess > 200) {
            printf("Illegal guess. Your guess must be between 1 and 200.\n");
            printf("Try again.\n ");
        }

        else if (currentGuess > number) {
                printf("Too high!\n");
        }


        else if (currentGuess < number) {
            printf("Too low!\n");

        }

        else {
            printf("****CORRECT****\n");
            return 0;
        }
    }

    return i;
}

int main() {


    int i, number, x;

    char answer = 'n';

    time_t t;

    srand((unsigned)time(&t));

    printf("Welcome to the game of Guess It! \nI will choose a number between 1 and 200. \nYou will try to guess that number.");
    printf("If you guess wrong, I will tell you if you guessed too high or too low. \nYou have 5 tries to get the number. \n");

    do
    {
        number = rand()%200+1;
        x = playGame(number);

        if (x == MAX_GUESS)
            printf("Sorry you have entered the maximum number of tries. \n");

        printf("Want to play again? \n");

        // To flush the newline character
        getchar();
        answer = getchar();

    } while (answer != 'n' || answer != 'N');

    printf("Goodbye, it was fun. Play again soon.\n");

    return 0;
}
NVS Abhilash
  • 574
  • 7
  • 24
  • Thank you! I hadn't thought of the do while loop since our teacher or book didn't mention it :) I just re-read the getchar() in my book and yes that makes more sense! – lizmart Jun 25 '17 at 05:38
  • @lizmart If the answer helped, you can accept the answer. – NVS Abhilash Jun 25 '17 at 05:41