-1
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <windows.h>
#include <stdlib.h>
#include <ctype.h>
#define PI 3.14159
#define PLANK_CONSTANT 6.626E-034
#define MASS_OF_ELECTRONS 9.109E-031
#define VELOCITY_OF_LIGHT 299800000

void hilo();

int main()
{
    char check;

    while (1)
    {
        hilo();
        printf("Would you like to play again (y/n)? ");
        scanf('%c', &check);
        if (check != 'y' || check != 'y')
        {
            break;
        }
    }

    system("pause");
    return 0;
}

void hilo()
{
    srand(time(NULL));

    int count = 0;
    int guess;
    int randomnumber = rand() % 101;

    while (1)
    {
        printf("Guess the number: ");
        scanf("%d", &guess);

        if (guess == randomnumber)
        {
            printf("Hooray, you have won!\n");
            break;
        }

        if (guess < randomnumber)
            printf("Wrong Number, Try again! The number you guessed is too low\n");
        if (guess > randomnumber)
            printf("Wrong Number, Try again! The number you guessed is too high\n");

        count++;

        if (count == 7)
        {
            printf("Sorry you lose, the number is: %d\n", randomnumber);
            break;
        }
    }
}

Can someone help me with this? After guessing the numbers for 7 times and "break" The C said there is an error "Exception thrown at 0x586A4B02 (ucrtbased.dll) in ALLlabs.exe: 0xC0000005: Access violation reading location 0x00002563."

I tried to search everywhere what's the problem with the break but I couldn't find what's the problem. Can you guys please tell me what's wrong with the code? You can copy the code to try to play with it yourself.

Mike
  • 4,041
  • 6
  • 20
  • 37
Key
  • 340
  • 2
  • 4
  • 10
  • 2
    Read your compiler warnings and pretend they are errors (most of the time they _are_ errors): `scanf('%c', &check);` -> `scanf("%c", &check);` – Jabberwocky Oct 02 '18 at 07:13
  • 1
    Actually you need `scanf(" %c", &check);` (note the space before `%c`). Read [this](https://stackoverflow.com/a/5240807/898348) for detailed information. – Jabberwocky Oct 02 '18 at 07:16
  • 2
    `srand(time(NULL));` must be called only once at the very begin (not in a loop). – David Ranieri Oct 02 '18 at 07:20
  • Thank you everyone for the help! srand function should be in the "main function" and scanf must be changed to scanf(" %c", &check); Really appreciate everyone's help! – Key Oct 02 '18 at 07:32

1 Answers1

2

It's this line:

scanf('%c', &check);

It's using single quotes - so the '%c' becomes a number, rather than a string.

Try this:

scanf(" %c", &check);

Remember to compile with all warnings enabled. Do not ignore a compiler warning!

There's some notes on using the space before "%c".

Kingsley
  • 14,398
  • 5
  • 31
  • 53