I've fixed the program. I'm not completey sure, but I believe my problem was using scanf to read in the input expecting it to be a %c - I thought this stood for character, but apparently I needed to be reading it in as a %s for string. I've since re-written the program to use a switch statement. I realize that this still has no error checking, and it can be broken easily, I'm sure (because scanf seems to be poorly designed) but this completes what the excersize in the book calls for. My assignment is now complete.
Thank you all for helping me in the right direction. Here's a post of my code incase someone catches something that I did not. I'm new to programming, so if you see a goof I've made, or something that I've made too complicated, give me a heads up and help me learn. I'm sure there's plenty of room for improvement with this simple game. Please note that I actually print the random number for debugging purposes. Since the program seems to be working as intended, this could be removed.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int i = 1;
int ran = 0;
int input = 0;
char cont = 0;
srand( time( NULL ) );
ran = 1 + ( rand() % 999);
printf("The random number is %d. This is for debugging purposes.\n", ran);
printf( "I have a number between 1 and 1000.\nCan you guess my number?\nPlease type your first guess.\n");
while( i != 0){
input = 0; /* Reset input. */
scanf( "%d", &input); /* Ask for input, and store it inside the variable input. */
/* If the input does not equal the random number, check this. */
if( input != ran ){
if( input > ran ){
printf("Too high. Please try again.\n");
}
if( input < ran ){
printf("Too low. Please try again.\n");
}
}
/* If the input does equal the random number, make a new random number. Ask if
the user wants to play another game. If not, end the program. */
if( input == ran){
ran = 1 + ( rand() % 999);
printf("Correct! Would you like to play again? ( y or n)\n");
scanf("%s", &cont);
switch(cont) { /* check the input inside of the variable cont */
case 'y':
case 'Y':
ran = 1 + ( rand() % 999);
printf("Starting new game.\n");
printf("The random number is %d. This is for debugging purposes.\n", ran);
printf( "I have a number between 1 and 1000.\nCan you guess my number?\nPlease type your first guess.\n");
break;
case 'n':
case 'N':
printf("Ending game.\n");
i = 0;
break;
default:
printf("Wrong input.\n");
break;
}
}
}
return 0;
}