Craps game - scanf automatically input huge number - c

The instructions for the part of the project I am having trouble with are:
"Playing" the game:
A second function playing() will be used to play a single game of craps until the player either wins or loses a bet, based upon the rules given above. This function should be modify the current $ amount of the player's bank roll according to the game result, modify the array values of the player won or lost, and whether the player bet for or against him/herself. Within the function, the player is asked whether s/he would like to place a bet. If so, the player must choose whether to bet "for" or "against" him/herself (see game rules above). The player then "rolls the dice" (simulated by a call to the dice-rolling function rolling()). This should be done interactively (via a key press from the player), rather than simply having the program continuously roll the dice until the game is over. After each roll, this function should report the two random dice values and the sum of the two. If, after the first roll, the game is not over, the player should be asked whether s/he would like to double the amount of the bet. When a roll causes the end of a game, the player is notified whether s/he won or lost money in that game overall, and the amount won or lost. In all other cases, the player is notified that s/he needs to roll again.
I have to code in a craps game that asks user for a bet amount and then they play craps. They have an initial bank roll of $100. I have to scan a bet amount in using scanf but it keeps making my bet amount very large without any user input. Can someone please help me, I have this project due tonight.
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h>
//function prototype
int rolling(void);
int playing(int c_amt);//inital money $100, min bet of $5, no max except money you have
void beginning(void);
void ending(void);
int
main()
{
printf("\nWelcome to Craps! Get ready to play!");
int bank_amt = 100;
char y_n = 'n';
do
{
bank_amt = playing(bank_amt);
if(bank_amt == 0)
{
printf("\nYou bet and lost all your money! You can't play anymore. Goodbye!");
exit(0);
}
if(bank_amt != 0)
{
printf("\nYour current balance is %d %d", &bank_amt, bank_amt);
printf("\nDo you want to play again? (y/n): ");
scanf("\n%c", &y_n);
}
}
while(y_n != 'n' && y_n != 'N');
}
int
rolling(void)
{
int dice1, dice2;
char roll;
srand((int)(time(NULL))); // "Seed" random number gen. with system time
printf("\nPress enter to roll the dice!");
fflush(stdin);
scanf("%c",&roll);
dice1 = 1+rand()%6; // random num from 1-6
dice2 = 1+rand()%6; // random num from 1-6
return dice1+dice2;
}
int
playing(int c_amt)
{
char gametype, y_n = 'n';
int total, point, for_u, against_u, winlose, win = 0, lose = 0;
int moneychange, bet_amt, final_amt;
printf("\nPlease press 'f' if you are betting for yourself and 'a' if your are betting against yourself.\n");
scanf("\n%c", &gametype);
do
{
printf("\nYour current bank balance is %d.", c_amt);
printf("\nEnter the amount you want to bet: ");
scanf(" %d", &bet_amt);
printf("Bet amount: %d", bet_amt);
if(bet_amt > c_amt || bet_amt < 5)
{
printf("\nYou dont have that much money or you placed a bet less than the minimum. Please place a proper bet.");
}
}
while(bet_amt > c_amt);
if (gametype == 'f' || gametype == 'F')
{
for_u++;
printf("\nYou are betting for yourself!\nLets get started!");
total = rolling();
printf("\nThe value rolled is %d.", total);
if (total == 7 || total == 11)
{
printf("\nGood job! You win :)");
winlose = 1;
}
else if (total == 2 || total == 3 || total == 12)
{
printf("\nCraps, you lose.");
winlose = 0;
}
else
{
point = total;
printf("\nYour point is %d.", point);
if(bet_amt*2 <= c_amt)
{
printf("\nWould you like to double your bet? (y/n)");
scanf("\n%c", &y_n);
}
if(y_n == 'y' || y_n == 'Y')
{
bet_amt = bet_amt*2;
}
do
{
total = rolling();
if(total == point)
{
printf("\nGood job! You win! :)");
winlose = 1;
break;
}
}
while(total != 7);
if(total == 7)
{
printf("You rolled a seven. You lose! :(");
winlose = 0;
}
}
}
else if (gametype == 'a' || gametype == 'A')
{
against_u++;
printf("You are betting against yourself!\nLet\'s get started!");
total = rolling();
printf("\nThe value rolled is %d.", total);
if (total == 2 || total == 3 || total == 12
{
printf("Good job! You win :)\n");
}
else if (total == 7 || total == 11)
{
printf("Craps, you lose.\n");
}
else
{
point = total;
printf("Your point is %d.\n", point);
if(bet_amt*2 <= c_amt)
{
printf("\nWould you like to double your bet? (y/n)");
scanf("\n%c", &y_n);
}
if(y_n == 'y' || y_n == 'Y')
{
bet_amt = bet_amt*2;
}
do
{
total = rolling();
if(total == 7)
{
printf("\nGood job! You win! :)");
winlose=1;
break;
}
}
while(total != point);
if(total == 7)
{
printf("You rolled a seven before making your point. You lose! :(");
winlose = 0;
}
}
}
if(winlose == 1)
{
final_amt = bet_amt + c_amt;
win++;
}
else
{
final_amt = c_amt - bet_amt;
lose++;
}
printf("Final amount is %d.", final_amt);
return final_amt;
}
Here is sample output:
Welcome to Craps! Get ready to play!
Please press 'f' if you are betting for yourself and 'a' if your are betting against yourself.
Your current bank balance is 100.
Enter the amount you want to bet: Bet amount: -1219958512
You dont have that much money or you placed a bet less than the minimum. Please place a proper bet.Final amount is 1219958612.
Your current balance is -1074871812 1219958612
Do you want to play again? (y/n):

Your formatting needs a lot of fixing to understand. However, the real issue is a buffer overflow, caused by not allocating enough memory to the char. Instead, I would suggest using simple int values like 0 and 1 to determine the player's choices.

Related

I don't understand why a part of my code isn't connecting to the rest

I have an assignment for a coding class where I have to create a code for the rock, paper scissors game, with different functions, calling rock 1 and paper 2 and scissors 3.
I also have to create a menu, then have the person chose, save that, then have the computer generate a random number and then print what they played, what the computer played and who won.
However, the last part isn't connecting, and I don't understand where I went wrong, so I'm really really lost and I would really appreciate any help.
For reference here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float response, choice;
int playerInput() {
printf(" For rock press 1\n ");
printf("For paper press 2\n ");
printf("For scissors press 3\n ");
printf("What would you like to play? ");
scanf("%f", &response);
return response;
}
int computerChoice() {
int lower = 1, upper = 3, count = 1;
srand(time(0));
printf("The random number that: ");
for (int i = 0; i < count; i++) {
int choice = (rand() % (upper - lower + 1)) + lower;
printf("the computer chose is %d ", choice);
}
return choice;
}
void displayWinner() {
if (response == choice) {
printf("You tied, lets play again");
}
if (choice == 1 && response == 2) {
printf("you won");
}
if (choice == 1 && response == 3) {
printf("computer won");
}
if (choice == 2 && response == 1) {
printf("computer won");
}
if (choice == 2 && response == 3) {
printf("you won");
}
if (choice == 3 && response == 1) {
printf("you won");
}
if (choice == 3 && response == 2) {
printf("computer won");
}
}
int main(void) {
int pinput, cinput, dinput;
pinput = playerInput();
cinput = computerChoice();
displayWinner();
return 0;
}
int choice =
But why declare a local with the same name as a global. I suggest that's your first mistake.
On fixing it you'll find the next line prints garbage because it's now printing a %d from a float (that got widened to a double).

Getting one loop for multiple characters using "while"

I'm new on Stackoverflow and I'm very, completely new to coding. Just messing around with C. Here's what I'm trying to do here (don't take this program scientifically accurate), this is a program that calculates for special relativity equations of length, mass and time. I have 3 questions actually:
When I try to put other characters in the y/n questions, everything works but for example if I enter "sfkl", the warning comes up 4 times because I entered 4 characters. And if I put space, it doesn't even give a warning until I put another character and then enter. Can I make it give 1 warning no matter how many characters I enter in one line (including space)?
My other question is, I kind of prevented inputting anything other than y/n but for the double value inputs (mass, length and time), I can't figure out a similar system (asking for a double value over and over again). Can you suggest me a solution?
And my third question is, when doing "scanf_s(" %c", &answer);", if I don't put a space before "%c", it doesn't work properly. It registers an enter and asks me to enter y/n only. Why need a space before that?
Here's the code:
#include <stdio.h>
#include <math.h>
#define LIGHT 299792458
int input();
int main()
{
printf("\n\n\tThis program calculates how length, mass and time changes with respect to your speed.\n\n\tThe values you enter are the quantites which are observed by a stationary observer and the output values are the quantites observed by the person in a vehicle which is moving at the speed that you enter.");
input();
return 0;
}
int input()
{
double length, mass, utime, speed;
char answer;
do
{
printf("\n\n **************************************************");
printf("\n\n\tPlease enter a quantity of length: ");
scanf_s("%lf", &length);
printf("\n\tPlease enter a quantity of mass: ");
scanf_s("%lf", &mass);
printf("\n\tPlease enter a quantity of time: ");
scanf_s("%lf", &utime);
printf("\n\tNow enter the speed of the vehicle (m/s): ");
scanf_s("%lf", &speed);
while (speed > LIGHT)
{
printf("\n\n\tNothing can surpass the speed of light in the universe. Enter a smaller value: ");
scanf_s("%lf", &speed);
}
double newlength = length * (sqrt(1 - pow(speed, 2) / pow(LIGHT, 2)));
double newmass = mass / (sqrt(1 - pow(speed, 2) / pow(LIGHT, 2)));
double newutime = utime / (sqrt(1 - pow(speed, 2) / pow(LIGHT, 2)));
if (speed == LIGHT)
{
printf("\n\n **************************************************");
printf("\n\n\n\tIt's technically impossible to reach the speed of light if you have mass but here are the mathematical limit results:\n\n\t*The new length quantity is 0\n\n\t*The new mass quantity is infinity\n\n\t*The new time quantity is infinity\n\n\n\t- Time successfully dilated -\n\n");
printf("\n\tDo you want to start over? (y/n): ");
scanf_s(" %c", &answer);
if (answer == 'n')
{
return 0;
}
else if (answer == 'y')
{
continue;
}
else
{
while (answer != 'y' && answer != 'n')
{
printf("\n\tPlease only enter 'y' or 'n': ");
scanf_s(" %c", &answer);
}
}
}
if (speed < LIGHT)
{
printf("\n\n **************************************************");
printf("\n\n\n\t*The new length quantity is %.20lf\n\n\t*The new mass quantity is %.20lf\n\n\t*The new time quantity is %.20lf\n\n\n\t- Time successfully dilated -\n\n", newlength, newmass, newutime);
printf("\n\tDo you want to start over? (y/n): ");
scanf_s(" %c", &answer);
if (answer == 'n')
{
return 0;
}
else if (answer == 'y')
{
continue;
}
else
{
while (answer != 'y' && answer != 'n')
{
printf("\n\tPlease only enter 'y' or 'n': ");
scanf_s(" %c", &answer);
}
}
}
}
while (answer == 'y');
return 0;
}
Thank you, have a good day
The return value of scanf is the number of elements parsed successfully; you can use this to repeat until something has been read successfully:
double nr=0;
while (!feof(stdin) && scanf("%lf",&nr)!=1) {
printf("not a number; try again.");
while ( (c = getchar()) != '\n' && c != EOF ) { }
}
Note that you have to take "invalid" input out of the buffer; otherwise, scanf would fail again and again.

How can I restart the program in C?

Hi I'm new to C and I wrote a simple program. I want to restart the program if the user picked the wrong choice, here is the code:
#include <stdio.h>
#include <cs50.h>
int main(void){
char choices;
float math, pc, svt, eng, philo;
do {
do {
printf("Enter your math score: ");
math = GetFloat();
}
while( math>20 || math<0);
do {
printf("Enter your pc score: ");
pc = GetFloat();
}
while(pc>20 || pc<0);
do {
printf("Enter your svt score: ");
svt = GetFloat();
}
while(svt>20 || svt<0);
do {
printf("Enter your eng score: ");
eng = GetFloat();
}
while(eng>20 || eng<0);
do {
printf("Enter your philo score: ");
philo = GetFloat();
}
while(philo>20 || philo<0);
printf("Are you pc or sm?\n");
printf("Write 1 for pc. 2 for sm\n");
int choice = GetInt();
if(choice == 1){
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if(choice == 2){
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else{
printf("You've picked the wrong choice \n");
}
printf("Do you want to try it again? (Y/N) ");
choices = getchar();
while (choices != '\n' && getchar() != '\n') {};
} while (choices == 'Y' || choices == 'y');
}
So what I mean here, I want to insert the code in the else block to restart the program and give the user another time. It would be very nice if I can just make him choose again between 1 or 2.
If you have any suggestions or improvement please don't hesitate to comment.
Thanks :)
What you need is do while loop surrounding choice code:
int choice;
do {
choice = GetInt();
if (choice == 1) {
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if (choice == 2) {
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else {
printf("You've picked the wrong choice, try again.\n");
}
} while(choice < 1 || choice > 2)
You already have a loop to try again, you can reuse that loop to get the user input again for choice. So, if the user enters choice other than 1 or 2, you can set choices = Y and redo the loop. without asking for user input.
Code is below.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
char choices;
float math, pc, svt, eng, philo;
do
{
// Other code here
int choice = GetInt();
if(choice == 1){
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if(choice == 2){
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else{
printf("You've picked the wrong choice \n");
choices = 'Y';
}
if ((choice == 1) || (choice == 2))
{
printf("Do you want to try it again? (Y/N) ");
choices = getchar();
while (choices != '\n' && getchar() != '\n') {};
}
} while (choices == 'Y' || choices == 'y');
}
Well, if somebody reading this has to actually restart their program for a more nontrivial reason (e.g. an exception handler, like me a couple of minutes ago), there is a portable way to to so in C, like so:
#include <setjmp.h> //from C standard library
jmp_buf restart_env;
int main() {
//some initialization you don't want to repeat
if(setjmp(restart_env)) {
//restarted, do whatever
}
//the code
}
void evenFromAnotherFunction() {
//...
if(something_that_justifies_this_approach) {
longjmp(restart_env, 1); //this restarts the program
//unreachable
}
//...
}
Note that you had better not use this if there's a better way. Using setjmp is bound to produce extremely annoying bugs. If you have no choice, remember that some data may preserve the value it had before calling setjmp for the first time, and some may not, so don't assume anything.

Random number game C

The game works fine my first time through, although; the second time it only gives you two lives... I have tried to change the number of lives but still can't figure out what I'm doing wrong.
// C_program_random_number_game
#include<stdio.h>
#include<time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int num1,x = 0;
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()%5 +1;
printf("\n\nEnter a number between 1 and 5 : ");
scanf("\n%d",&num1);
x++;
if(num1 > 0 && num1 < 5)
{
do
{
if(num1 < r)
{
printf("\nClose! try a little higher... : ");
x++;
}
else if (num1 > r)
{
printf("\nClose! try a little lower...: ");
x++;
}
scanf("%d",&num1);
}while(num1!=r && x <3);
if(num1 == r)
{
printf("\nWinner! >> you entered %d and the computer generated %d! \n",num1, r);
}
else if(num1 != r)
{
printf("\nBetter luck next time!");
}
printf("\n\nWould you like to play again? (y or n) : ");
scanf("\n%c",&replay);
}
else
{
printf("Sorry! Try again : ");
scanf("%d",&num1);
}
}while(replay == 'y'|| replay == 'Y');
}
else if (game == 'n' || game == 'N')
{
printf("Okay, maybe next time! ");
}
else
{
printf("Sorry, invalid data! ");
}
return 0;
}
There are all kinds of issues with you code (most of them are minor in terms of programming). Most of the errors are typos in what you want done via this question and what you printf().
As is, this code will random between 1-25, accept an input of any valid int, see if you matched it, and only give you 5 tries. (I didn't add error checking to enforce that the input is between 1-25. That should probably be added.)
I commented my code below with all my changes and went by that you had in the printf()s.
Note: See my comments above for explanations of my changes since I already pointed them out. I also formatted it so its a little more easy to read.
Note2: I did this quickly using an online compiler. If you find anything wrong with this or not working as you'd like, just comment below and I'll address it.
// C_program_random_number_game
#include<stdio.h>
#include<time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int num1,x = 0;
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 25 : ");
scanf("%d",&num1);
do
{
printf("r = %d\n", r);
if(num1 < r)
{
printf("\nClose! try a little higher... : ");
x++; //Increment x if wrong guess
}
else if (num1 > r)
{
printf("\nClose! try a little lower...: ");
x++; //Increment x if wrong guess
}
scanf("%d",&num1);
}while(num1!=r && x < 5); //If x is 5 or more, they ran out of guesses (also, you want an && not an ||)
if(num1 == r) //Only print "winner" if they won!
{
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;
}
There are a combination of two problems. The first is that you're not breaking out of the "for" loop when the number matches. Therefore the match is only checked on every third guess.
The second problem is in this logic check:
}while(num1!=r || x <= 3);
We see that this turns into "true" if the for loop is broken out of early.

Monty hall show simulation unexpected results

#include <stdio.h>
#include <time.h>
int main (void)
{
int pickedDoor, remainingDoor, hostDoor, winningDoor, option, games = 0, wins = 0;
float frequency = 0;
srand (time(NULL));
while (1)
{
printf ("Pick one of the three doors infront of you, which do you want?\n");
scanf ("%d", &pickedDoor);
if (pickedDoor > 3 || pickedDoor <= 0)
{
break;
}
winningDoor = rand() % 3 + 1;
do
{
hostDoor = rand() % 3 + 1;
} while (hostDoor == pickedDoor || hostDoor == winningDoor);
do
{
remainingDoor = rand() % 3+1;
} while (remainingDoor == pickedDoor || remainingDoor == hostDoor);
printf ("The door the host picked is %d\n", hostDoor);
do
{
printf("Do you want to switch doors? Please enter in the door you want:\n", hostdoor);
scanf("%d", &option);
if (option > 3 || option <= 0)
{return 0;}
}while (option == hostDoor);
if (option == winningDoor)
{
printf("You Won!\n");
wins++;
}
else
{
printf("YOU LOSE!\n");
}
games++;
}
frequency = ((float) wins / games) *100;
printf ("The number of games that you won is %d\n", wins);
printf ("The frequency of winning is %.0f%%\n", frequency);
return 0;
}
Hi, this is my version of the monty hall game show, im getting unexpected results though.
sometimes when I enter in a door for my option it just brings me back to the "pick one of the three doors infront of you" statement, when it should tell me if i have won or lost.
I think this is because the "option" door is equal to the "hostDoor.
I thought having "option != hostDoor" would fix it but it does not.
If i am correct in that assumption how can I fix it? If not why is it not working and how can I fix it?
To simulate correctly, OP needs to show the host door.
do {
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
if (option > 3 || option <= 0 ) {
return 0;
}
} while (option == hostDoor);
// instead of
#if 0
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
if (option > 3 || option <= 0 ) { return 0; }
#endif
To deal with OP " it should tell me if i have won or lost." problem, change
else if (option == remainingDoor)
to
else
Your scanf("%d", &option) is OK. I prefer the fgets()/sscanf() combo and its alway useful to check the result of scanf() family, but that is not your issue here.
Its because of these:
scanf ("%d", &pickedDoor);// reads \n after the last input
scanf("%d", &option); // reads \n after the last input
**option != hostDoor; // completely useless .. get rid of it**
I would suggest putting a getchar() after each scanf to get rid of the \n character
so something like this:
#include <stdio.h>
#include <time.h>
int main (void)
{
int pickedDoor, remainingDoor, hostDoor, winningDoor, option, games = 0, wins = 0;
char collect; //variable to collect any extra input like \n
float frequency = 0;
srand (time(NULL));
while (1)
{
printf ("Pick one of the three doors infront of you, which do you want?\n");
scanf ("%d", &pickedDoor);
collect = getchar(); // get rid of the \n from the input stream
printf("collect = %c\n",collect);
if(collect!='\n'){ // is it actually a \n or did you take in something else
putchar(collect); // if it isn't \n put it back
}
if (pickedDoor > 3 || pickedDoor <= 0)
{
break;
}
winningDoor = rand() % 3 + 1;
do
{
hostDoor = rand() % 3 + 1;
} while (hostDoor == pickedDoor || hostDoor == winningDoor);
do
{
remainingDoor = rand() % 3+1;
} while (remainingDoor == pickedDoor || remainingDoor == hostDoor);
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
collect = getchar(); // get rid of the \n from the input stream
printf("collect = %c\n",collect);
if(collect!='\n'){ // is it actually a \n or did you take in something else
putchar(collect); // if it isn't \n put it back
}
if (option > 3 || option <= 0 )
{
return 0;
}
if (option == winningDoor)
{
printf("You Won!\n");
wins++;
}
else if (option == remainingDoor)
{
printf("YOU LOSE!\n");
}
games++;
}
frequency = ((float) wins / games) *100;
printf ("The number of games that you won is %d\n", wins);
printf ("The frequency of winning is %.0f%%\n", frequency);
return 0;
}
Another more efficient way would be to use fgets or to have error checks on scanf() itself
srand and rand belongs to stdlib header file
#include<stdlib.h> // include this header file
option != hostDoor; // this statement does not do anything
and your else if (option == remainingDoor) should be else { printf("you lose");}

Resources