# Thread: Random Number Guessing Game

1. ## Random Number Guessing Game

Code:
```#include <conio.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#define MAX 100

int GetGuess();
void random();
int play(int guess1, int answer1);
int compare(int guess1, int answer1);

int guess1;
int answer1;

int main()
{
int answer;
random();
FILE *inptr;
inptr = fopen("File1.txt","r");
answer1 = fscanf(inptr,"%d", &answer);
play(guess1,answer1);
getch();
}
int play(int guess1, int answer1)
{
guess1 = GetGuess();
compare(guess1, answer1);

}

int GetGuess ()
{
int guess;
printf("Enter your guess:\n");
scanf("%d",&guess);
return guess;
}

int compare(int guess1, int answer1)
{
if (answer1 == guess1)
{
printf("Congratulations you are a lucky winner\n");
}
else
{
printf("not working");
}

}

void random()
{
//declare variables
int i;
int num;
FILE *bzvz;
//open file to save numbers
bzvz=fopen("File1.txt","w");
srand(time(NULL));//seeds the number generator to randomize
//for(i=0;i<20;i++)
//{
num = rand()%MAX +1;//calculates a random number from 1 and 10
fprintf(bzvz,"%d ",num);
//}
fclose(bzvz);
}```

I am completely stuck when assigning values to and passing variables around. It seems that the problem occurs with fscanf function. I have also guessed that it might be passing and reading it as a character, even though I said it will be an integer, and tried atoi() with no luck. I troubleshooted the error as I tried to print the given values after I assign it, with no luck. I am doing this for a friend I have recently been programming django, so I am completely out of the loop when it comes to C. Can someone please help me diagnose or point me to where I am assigning converting passing in a wrong way?

Thank you.

2. > answer1 = fscanf(inptr,"%d", &answer);
> play(guess1,answer1);
answer1 is the success/failure status of the fscanf call.
Since you're trying to read one thing, possible values for answer1 are 1, 0 or EOF

answer (only if answer1 == 1) is the number read from the file.
You probably want to use this number to play.

3. Welcome to the forum, Borko!

line #24 is a problem. You are putting the value from the file, into answer -- and then you never use it. The answer1 variable is going to be given the number of items that fscanf() has scanned and assigned a value to.

So change &answer in that line, to &answer1, and let answer get assigned the value from fscanf(), on the left side of the equal sign.

Since guess1 is global, you don't have to pass it in a parameter, and you can assign it a value, in any function. GetGuess() doesn't have to return the guess, it can be assigned to guess1, right inside GetGuess.

See how that works, now.

Popular pages Recent additions