Hi there, I'm a newbie and trying to go through a tutorial question that I can't seem to get. The book I'm using did a random number generator/guessing game and I rewrote it using my own understanding of the code. However, I can't figure out why the code runs twice after the initial run. That is, the first time it runs, if you hit y to run it again, it outputs to the console as though it has gone through twice each time.
I have attached my code below; I apologize in advanced if I have made any silly mistakes:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int randomNumber;
int guessNumber;
char playAgain = ' ';
BOOL looper = TRUE;
NSLog(@"Welcome to the random number generator!");
while (looper)
{
randomNumber = (random()%101);
NSLog(@"The random number is %d",randomNumber);
/*NSLog(@"Guess a number:");
scanf("%d",&guessNumber);*/
/*if (guessNumber > randomNumber)
{
NSLog(@"Your guess was too high, guess again:");
scanf("%d",&guessNumber);
}*/
/*if (guessNumber < randomNumber)
{
NSLog(@"Your guess was too low, guess again:");
scanf("%d",&guessNumber);
}*/
/*else
{
NSLog(@"Correct!");
}*/
NSLog(@"Play again?");
scanf("%c",&playAgain);
if (playAgain == 'n')
{
looper = FALSE;
}
}
[pool drain];
return 0;
}
Also, forgot to add that when I uncomment the code at the top of the main while loop, I can no longer input a character for scanf("%c",&playAgain); the code just runs right through.
I have attached my code below; I apologize in advanced if I have made any silly mistakes:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int randomNumber;
int guessNumber;
char playAgain = ' ';
BOOL looper = TRUE;
NSLog(@"Welcome to the random number generator!");
while (looper)
{
randomNumber = (random()%101);
NSLog(@"The random number is %d",randomNumber);
/*NSLog(@"Guess a number:");
scanf("%d",&guessNumber);*/
/*if (guessNumber > randomNumber)
{
NSLog(@"Your guess was too high, guess again:");
scanf("%d",&guessNumber);
}*/
/*if (guessNumber < randomNumber)
{
NSLog(@"Your guess was too low, guess again:");
scanf("%d",&guessNumber);
}*/
/*else
{
NSLog(@"Correct!");
}*/
NSLog(@"Play again?");
scanf("%c",&playAgain);
if (playAgain == 'n')
{
looper = FALSE;
}
}
[pool drain];
return 0;
}
Also, forgot to add that when I uncomment the code at the top of the main while loop, I can no longer input a character for scanf("%c",&playAgain); the code just runs right through.
Last edited: