calling scanf inside do while loop is breaking the loop - c

I have a do while loop. When I run it without scanf(), it runs properly. But if I enter a scanf() it breaks the loop! Why???
The code:
With scanf()
void main(){
int num = prng() % 100, guessed, guesses = 0;
bool win = false;
printf("The Game Begins. You Have To Guess A Number\n");
do{ //A do while loop untill the user guesses the correct number
printf("Guess a number\n");
scanf("%d", guessed);
guesses++;
}while (!check(guessed, num));
printf("Yayy!!! You won the game in %d guesses!!", guesses); //Message after guessing the correct number
return;
}
This breaks the loop instantly:
> .\a.exe
The Game Begins. You Have To Guess A Number
Guess a number
5
>
But when I run it without the scanf()
void main(){
int num = prng() % 100, guessed, guesses = 0;
bool win = false;
printf("The Game Begins. You Have To Guess A Number\n");
do{ //A do while loop untill the user guesses the correct number
printf("Guess a number\n");
guessed = num;
// scanf("%d", guessed);
guesses++;
}while (!check(guessed, num));
printf("Yayy!!! You won the game in %d guesses!!", guesses); //Message after guessing the correct number
return;
}
It works fine!!
> .\a.exe
The Game Begins. You Have To Guess A Number
Guess a number
Hurrayyy!!!! You got the number!!!!!!!!!Yayy!!! You won the game in 1 guesses!!
>
Can you explain what is the actual problem?

You need to add & in front of guessed variable within the scanf function.
scanf("%d", &guessed);
An explanation of how scanf works can be seen here.

Related

C Programming Guessing Game

I need help finishing my program. I can't seem to get the last step, when the user enters 'y' to play another game it should start again. If the user enters 'n' then it should end. Thank you in advance for any help. Below is the code I have so far.
Here is the problem:
Write a C program that plays a number guessing game with the user.
Below is the sample run:
OK, I am thinking of a number. Try to guess it.
Your guess? 50
Too high!
Your guess? 250
Illegal guess. Your guess must be between 1 and 200.
Try again. Your guess? 30
**** CORRECT ****
Want to play again? y
Ok, I am thinking of a number. Try to guess it.
Your guess? 58
**** CORRECT ***
Want to play again? n
Goodbye, It was fun. Play again soon.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i, number, currentGuess, MAX_GUESS = 5;
int answer = 'n';
time_t t;
srand((unsigned) time(&t));
number = rand() % 200 + 1;
printf("Welcome to the game of Guess It! \nI will choose a number between 1 and 200. \nYou will try to guess that number.");
printf("If you guess wrong, I will tell you if you guessed too high or too low. \nYou have 5 tries to get the number. \n");
printf("\nOK, I am thinking of a number. Try to guess it. \n");
for (i = 0; i < MAX_GUESS; i++) {
printf("\nYour guess?");
scanf("%i", &currentGuess);
if (currentGuess > 200) {
printf("Illegal guess. Your guess must be between 1 and 200.\n");
printf("Try again.\n ");
}
else if (currentGuess > number) {
printf("Too high!\n");
}
else if (currentGuess < number) {
printf("Too low!\n");
}
else {
printf("****CORRECT****\n");
return 0;
}
}
printf("Sorry you have entered the maximum number of tries. \n");
printf("Want to play again? \n");
scanf("%i", &answer);
if(answer == 'n') {
printf("Goodbye, it was fun. Play again soon.\n");
return 0;
}
else if (answer != 'n') {
printf("Ok, I am thinking of a number. Try to guess it.\n");
}
}
Here's an idea for you to do this in your code:
char answer = 'y';
do
{
// ...
printf( "Want to play again (y/n)? " );
scanf( " %c", &answer );
// Mind ^ the space here to discard any
// previously read newline character
} while ( answer == 'y' );
Check the below code, you might wanna understand the code, rather than just copy pasting it.
The code delegates the task of doing a repetitive task to a function.
The code then relies on the function to say how many chances player has played, or -1 for successful.
And note the getchar() rather than scanf.
NOTE: The extra getchar() is needed, because I don't know but taking character input after taking integer input puts a '\n' character in the stdin, which results in unwanted behaviour. So this is a small trick I always use to tackle such cases.
Pay attention to the do while loop, this case becomes a classic example where you should use do while loop.
Also I have used macros to define MAX_GUESS. That's a good practice. You might wanna google it for "why?"
If you have any further queries, do comment in the answer.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#define MAX_GUESS 5
int playGame(int number)
{
printf("\nOK, I am thinking of a number. Try to guess it. \n");
int i, currentGuess;
for (i=0; i<MAX_GUESS; i++){
printf("\nYour guess?: ");
scanf("%i", &currentGuess);
if (currentGuess > 200) {
printf("Illegal guess. Your guess must be between 1 and 200.\n");
printf("Try again.\n ");
}
else if (currentGuess > number) {
printf("Too high!\n");
}
else if (currentGuess < number) {
printf("Too low!\n");
}
else {
printf("****CORRECT****\n");
return 0;
}
}
return i;
}
int main() {
int i, number, x;
char answer = 'n';
time_t t;
srand((unsigned)time(&t));
printf("Welcome to the game of Guess It! \nI will choose a number between 1 and 200. \nYou will try to guess that number.");
printf("If you guess wrong, I will tell you if you guessed too high or too low. \nYou have 5 tries to get the number. \n");
do
{
number = rand()%200+1;
x = playGame(number);
if (x == MAX_GUESS)
printf("Sorry you have entered the maximum number of tries. \n");
printf("Want to play again? \n");
// To flush the newline character
getchar();
answer = getchar();
} while (answer != 'n' || answer != 'N');
printf("Goodbye, it was fun. Play again soon.\n");
return 0;
}

How do I get my code from going into an infinte loop?

I am rewriting the Guessing Game code from 'C Programming for Absoulute Beginners' to verify that the user has entered in a digit, using the isdigit() function.
The rest of the code works, in terms of error checking; but the moment that the user enters in a non-digit, the code goes into an infinite loop.
#include <stdio.h>
#include <stdlib.h>
#define NO 2
#define YES 1
main()
{
int guessGame;
guessGame = 0;
int iRandomNum = 0;
int iResponse = 0;
printf("\n\nWould you like to play \"The Guessing Game\"?\n\n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
do{
if(guessGame == YES){
iRandomNum = (rand() % 10) + 1;
printf("\nGuess a number between 1 and 10:\n\n ");
scanf("%d", &iResponse);
if(!isdigit(iResponse)){
printf("\nThank you\n");
printf("\nYou entered %d\n", iResponse);
if(iResponse == iRandomNum){
printf("\nYou guessed right\n");
printf("\nThe correct guess is %d!\n", iRandomNum);
printf("\nDo you wish to continue? \n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
} else {
printf("\n\nSorry, you guessed wrong\n");
printf("\nThe correct guess was %d!\n", iRandomNum);
printf("\n\nDo you wish to continue? \n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
}
}
else {
printf("\nYou did not enter a digit\n");
printf("\n\nPlease enter a number between 1 and 10:\n\n");
scanf("%d", &iResponse);
}
}
else {
printf("\nThe window will now close. Try again later!\n");
exit(0);
}
}while(guessGame != NO);
}
The code goes into infinite loop as scanf() is unable to read an integer. The character you entered remains in the keyboard buffer.No more reading of integers is possible as long as the character is present in the buffer. scanf() simply returns the number of items read as 0 each time. Hence,the program does not wait for the user to enter data and infinite loop results.
scanf() returns number of items successfully read. So,you can simply check for the return value of scanf(), if its 1 then scanf() has correctly read an integer.
check = scanf("%d", &iResponse);
if(check == 1){
printf("\nThank you\n");
printf("\nYou entered %d\n", iResponse);
and flush the buffer if wrong input is entered
else {
while (getchar() != '\n'); //flush the buffer
printf("\nYou did not enter a digit\n");
printf("\n\nPlease enter a number between 1 and 10:\n\n");
//scanf("%d", &iResponse);
}
no need to ask for input here, while loop will continue and prompt for input in the beginning
Trying taking the input in the form of string .. also u will have to compare the input in the form 'number' :)

Two questions, why the double print and how to start it over again! C programming

I'm writing the simplest game in C - Number guessing game. The game itself works good. Yaay me. The problem is that I don't know how to start it over. See code below:
int main()
{
int number, innum, times = 0;
char playAgain;
srand((unsigned)time(NULL));
number = 5;//rand() % 1000;
for(;;)
{
while(innum != number)
{
printf("Enter a number: ");
scanf("%d", &innum);
if(innum > number)
printf("The entered number is too big!\n");
if(innum < number)
printf("The entered number is too small!\n");
times++;
if(innum == number)
{
printf("Congrats you guessed right!\n");
printf("It took you %d tries\n", times);
}
}
printf("Do you want to play again?");
scanf("%c", &playAgain);
if(playAgain == 'n')
break;
}
return 0;
}
The first problem is that it prints "Do you want to play again?" two times. Why is that? And the other problem is, how do I get the game to start again?
Thanks in advance.
This should work for you:
(What i did? Added a space by the scanf and put the declaration of number, times and innum in the for loop)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int number, innum, times;
char playAgain;
srand((unsigned)time(NULL));
for(;;) {
/*Declare the variables here*/
number = 5; //rand() % 1000;
innum = 0;
times = 0;
while(innum != number) {
printf("Enter a number: ");
scanf("%d", &innum);
if(innum > number)
printf("The entered number is too big!\n");
if(innum < number)
printf("The entered number is too small!\n");
times++;
if(innum == number) {
printf("Congrats you guessed right!\n");
printf("It took you %d tries\n", times);
}
}
printf("Do you want to play again?");
scanf(" %c", &playAgain);
//^Added space here to 'eat' any new line in the buffer
if(playAgain == 'n')
break;
}
return 0;
}
possible output:
Enter a number: 2
The entered number is too small!
Enter a number: 6
The entered number is too big!
Enter a number: 5
Congrats you guessed right!
It took you 3 tries
Do you want to play again?y
Enter a number: 3
The entered number is too small!
Enter a number: 5
Congrats you guessed right!
It took you 2 tries
Do you want to play again?n

How to make the program restart if I press a certain button

I've recently written this "guess the number" program. My problem is that I want the program to restart when I press "y" after the "Play again" question comes. Any ideas? :)
srand( time(NULL) );
int secretNumber = rand()%100 + 1;
int guess = 0;
int counter = 0;
printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");
while(1)
{
counter++;
scanf("%d", &guess);
if (guess == secretNumber)
{
printf("It took you %d tries\n", counter);
printf("Play again (y/n)?\n");
break;
}
if (guess < secretNumber)
{
printf("Too low!\n");
}
if (guess > secretNumber)
{
printf("Too high!\n");
}
Put the entire code snippet you have inside another while(1) statement:
srand(time(NULL));
while(1)
{
int secretNumber = rand()%100 + 1;
int guess = 0;
int counter = 0;
printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");
while(1)
{
//code for guessing number
}
printf("Play again? ");
if (getchar() != 'y')
{
break;
}
}
This
printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");
needs to be inside your loop, unless you only want to give them one guess.
The easiest way to do what you want is to create a new secret number when they guess right, and bail out of your loop if they answer "No" to "do you want to play again?"
You can use another variable. like below.
char userinput = 'y';
while(input == 'y')
{
//your logic here
//And at the end use one scanf
printf("Play again (y/n)?\n");
scanf("%c", &userinput);
}
You need to add one new variable, In above case it's userinput.
use a while loop, with a loop variable of type bool say dec initially True. Put your code and initialize all the variables inside the loop, so that they can have a local scope and gets destroyed each time the loop is complete. Ask user for the dec variable if it presses "y" set it to True else set it to False. so that the loop may be skipped this time
code may be like :
char cha;
bool dec=True;
while(dec){
srand( time(NULL) );
int secretNumber = rand()%100 + 1;
int guess = 0;
int counter = 0;
printf("I'm thinking of a number between 1 and 100\n");
printf("What is your guess?\n");
while(1)
{
//code for guessing number
}
printf("Play again? ");
scanf("%c",&cha);
if (char== 'y')
bool=True;
else bool=False;
}

Simple random numbers game program

Here is my code, It is a simple number game where the user tries to guess the random number however, I can not figure out why it you never win..There are two things i am having trouble solving 1) The user never guesses the correct number 2) I want to have a cap of 3 tries of guessing although I cant seem catch what i'm overlooking
// C_program_random_number_game
#include<stdio.h>
#include<time.h>
#include <stdlib.h>
int main(){
srand(time(NULL));
int num1,x;
char game, cont, replay;
printf("Would you like to play a game? : ");
scanf("%c",&game);
if (game == 'y' || game == 'Y'){
printf("\nThe rules are simple. You have have 5 tries to guess the computers number. \n \n If you succeed you win the game, if you dont you lose the game. Good luck!");
do{
int r = rand()%25 +1;
printf("\n\nEnter a number between 1 and 5 : ");
scanf("%d",&num1);
do{
for(x=1; x<=3; x++){
if(num1 < r){
printf("\nClose! try a little higher... : ");
}
else if (num1 > r){
printf("\nClose! try a little lower...: ");
}
scanf("%d",&num1);
}
}while(num1!=r || x <= 3);
printf("\nWinner! >> you entered %d and the computer generated %d! \n",num1, r);
printf("\nWould you like to play again? (y or n) : ");
scanf("\n%c",&replay);
}while(replay == 'y'|| replay == 'Y');
}
printf("Thanks for playing! ");
if (game == 'n' || game == 'N'){
printf("Okay, maybe next time! ");
}
return 0;
}
One definite problem is that the format specifier is incorrect:
scanf("&d",&num1);
should be:
scanf("%d",&num1);
Moreover, the last 2 conditions in your while loop would never be evaluated since it'd not enter the loop if the guess is equal to the random number. Use a do-while loop instead to loop infinitely, and break out of it as per the user input. Remember to take user input for the guess within the loop.
There are various flaws, here is the code you are looking for:
while(num1 != r){
if(num1 < r){
printf("higher... : ");
}
else{
printf("lower...: ");
}
scanf("%d",&num1);
}
printf("Winner! >> you entered %d and the computer generated %d! \n",num1, r);
printf("Would you like to play again? (y or n) : ");
scanf("%c",&replay);
As I pointed out in the comment above, previously, inside the while loop, there would never be a time when num1==r and thus the if statement inside will never be true. Now, the loop jsut simply stops after it reaches the number.

Resources