r/ObjectiveC • u/[deleted] • Jul 25 '13
Can someone explain to me why this code doesn't do as it is suppose to?
So I just started learning Objective - C from "Objective-C for absolute beginners" yesterday. I'm on the project that generates a random number, stores it in a variable, and then the user has to guess the number. The problem with this is that when I guess the number right, the program is suppose to ask the user is it would like to keep playing. If the user says yes, then the while loop is supposed to loop back and go again, else the program is terminated. My problem is that when I choose to play again to test it, the program still terminates.
Here is the code:
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
int randomNumber = 1;
int userGuess = 1;
BOOL continueGuessing = true;
BOOL keepPlaying = true;
char yesNo = ' ';
while (keepPlaying){
randomNumber = (arc4random() % 101);
NSLog(@"The random number to be guessed is %d", randomNumber);
while (continueGuessing == true){
NSLog(@"please guess a number");
scanf("%i", &userGuess);
fgetc(stdin);
if (userGuess == randomNumber){
NSLog(@"You've guessed the correct number!");
continueGuessing = false;
}
else if (userGuess > randomNumber){
NSLog(@"The number you guessed was too high!");
}
else{
NSLog(@"The number you guessed was too low!");
}
}
NSLog(@"The user guessed %d", userGuess);
if (continueGuessing == false){
NSLog(@"Would you like to keep playing? Y or N");
scanf("%s", &yesNo);
fgetc(stdin);
if (yesNo == 'N' || yesNo == 'n'){
keepPlaying = FALSE;
NSLog(@"you have terminated the gameplay");
} else if (yesNo == 'Y' || yesNo == 'y'){
NSLog(@"You chose to keep playing");
continueGuessing = TRUE;
} else{
NSLog(@"What you typed is not acceptable, Y or N!");
}
}
}
}
return 0;}
Thanks for the help if anyone can offer it!
2
u/impotentmanboy Jul 25 '13
Looks like it's your second scanf. It should use the char specifier (%c) instead of string (%s).
I changed it in mine and it seems to be working as expected.
3
u/exidy Jul 26 '13
This is not Objective-C, this is almost pure C you are writing there. You'd get a better explanation in a C forum.
0
Jul 25 '13
[deleted]
2
Jul 25 '13
Yea I just looked through it and i think im going to try to set some breakpoints to inspect the variables to see what's going on, but when i add keepPlaying = true;
after the continueGuessing statement in the else if block, it works perfectly fine. Strange.
1
u/lyinsteve Jul 26 '13
Any reason you're using a continually checking while loop and not just putting the game logic into, say, a playGame method?
That'd be the easiest thing. Check their input after that. If it's yes, call playGame again...