I've only been using c for a couple of weeks, so there will very likely be obvious errors I've overlooked. I've looked at other threads, but I don't understand a lot of what I'm reading.
The program assumes an infinitely large deck.
KNOWN ISSUES:
clearBuffer isn't currently in use, I am trying different things.
dealerhand doesn't add values properly.
compare function doesn't exist yet.
Multiple non numeric inputs result in repeating of error message.
Attempting to "hit" crashes program.
Current code:
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int deal()
{
unsigned long timenow;
timenow = time(NULL);
srand(timenow);
int deck[] ={2,3,4,5,6,7,8,9,10,10,10,10,11};
return deck[rand() % 13];
printf("%d\n", deal());
}
void clearBuffer(){
char ch;
while ((ch = getchar()) != '\n' && ch != EOF);
}
int dealerhand()
{
int dealerhand[10];
int dealertotal = 0;
while (dealertotal < 17)
{
dealertotal = deal();
printf("%d\n dx", deal());
dealertotal = dealertotal + deal();
printf("%d\n D", dealertotal);
}
}
int playerhand()
{
int playerhand [10];
int i;
for(i=0; i<1; i++)
{
playerhand[i] = deal();
printf(" %d\n", playerhand[i]);
}
}
int hit()
{
int i;
int playerhand[10];
playerhand[i] = deal();
printf(" %d", playerhand[i]);
}
int main()
{
int hold = 1;
int num;
int num2;
int money = 500;
printf("Welcome to Blackjack! You have $500. Play a hand? 1=y 2=n. ");
while (hold = 1)
{
scanf ("%d",&num);
if (num == 1)
{
printf("Great! Ante is $20, here's your hand!");
playerhand();
playerhand();
dealerhand();
money = money - 20;
printf("You have %d dollars. Hit? 1=y 2=n", money);
//clearBuffer();
scanf("%d", num2);
if (num2 = 1)
{
playerhand();
break;
}
if (num2 = 2)
{
// compare();
}
}
if (num == 2)
{
printf("Too bad, come back soon!");
break;
}
if (num != 1 || num != 2)
{
printf("Sorry what was that? Play a hand? 1=y 2=n.");
while((num = getchar()) =! EOF && num != '\n');
}
}
}
I tried to correct this but it have many issue see following source and try to correct your logical errors, this is best I can do for you:
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int deal(void)
{
int deck[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11};
return deck[rand() % 13];
}
void clearBuffer(void)
{
char ch;
while ((ch = getchar()) != '\n' && ch != EOF);
}
int dealerhand(void)
{
int dealerhand[10];
int dealertotal = 0;
while (dealertotal < 17) {
dealertotal = deal();
printf("%d\n dx", deal());
dealertotal = dealertotal + deal();
printf("%d\n D", dealertotal);
}
/* RETURN INT ... */
}
int playerhand(void)
{
int playerhand[10];
int i;
for (i = 0; i < 10; i++) {
playerhand[i] = deal();
printf(" %d\n", playerhand[i]);
}
/* RETURN INT ... */
}
int hit(void)
{
int i;
int playerhand[10];
/* I think you need for here ... */
for (i = 0; i < 10; i++) {
playerhand[i] = deal();
printf(" %d", playerhand[i]);
}
/* RETURN INT ... */
}
int main(int argc, char *argv[])
{
srand((unsigned)time(NULL));
int hold = 1;
int num;
int num2;
int money = 500;
printf("Welcome to Blackjack! You have $500. Play a hand? 1=y 2=n. ");
while (hold == 1) {
scanf("%d", &num);
if (num == 1) {
printf("Great! Ante is $20, here's your hand!");
playerhand();
playerhand();
dealerhand();
money = money - 20;
printf("You have %d dollars. Hit? 1=y 2=n", money);
scanf("%d", &num2);
if (num2 == 1) {
playerhand();
break;
}
if (num2 == 2);
/* compare(); */
}
if (num == 2) {
printf("Too bad, come back soon!");
break;
}
if (num != 1 || num != 2) {
printf("Sorry what was that? Play a hand? 1=y 2=n.");
while (((num = getchar()) != EOF) && num != '\n');
}
}
}
Related
The code that I wrote underneath the if statement- if(noMoreGuesses == 1) -is not executing if guessAmount >= guessLimit. I end up just being able to enter in a bunch of numbers without limit. I'm new to c, so if somebody could point out what I am doing wrong I would really appreciate it.
#include <stdio.h>
#include <stdlib.h>
int main() {
int guess;
int guessNumber = 5;
int guessAmount = 0;
int guessLimit = 4;
int noMoreGuesses = 0;
while (guess != guessNumber) {
if (guessAmount >= guessLimit) {
noMoreGuesses = 1;
}
else {
printf("Please enter a number: ");
scanf("%d", &guess);
guessAmount++;
}
}
if (noMoreGuesses == 1) {
printf("You used up all your guesses!\n");
}
else {
printf("You win!");
}
}
As you have used the guess variable before its declaration the problem may occur. The below modified code works fine.
#include <stdio.h>
int main()
{
int guess;
int guessNumber = 5;
int guessAmount = 0;
int guessLimit = 4;
int noMoreGuesses = 0;
while (1) {
if (guessAmount >= guessLimit) {
noMoreGuesses = 1;
break;
}
else {
printf("Please enter a number: ");
scanf("%d", &guess);
guessAmount++;
}
}
if (noMoreGuesses == 1) {
printf("You used up all your guesses!\n");
}
else {
printf("You win!");
}
}
So I am writing a gambling program for my c programming class. Essential its a menu for a dog track and you have to place a wager, select a dog, and the program chooses a winner and tells you if you won (how much) or lost. I use the ran() function but a specific dog that I set to win 10% of the time wins more than any other dog (including one that should win 40% of the time).
/*Programmer: John S. Bolen*/
/*Date: 3/1/19*/
/* User Will Choose to gamble, View Results, Or Quit program.
There are 9 Dogs to Chose from with a set %chance to win and
a set Payout Rate */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#define SIZE 1000
#define PAUSE system("pause")
#define CLS system("cls")
#define FLUSH nothingFlush()
#define SIZE 1000
void nothingFlush() {
char nothing;
while (scanf("%c", ¬hing) == NULL);
}
typedef struct {
char name[100];
float payout;
float winOdds;
} DOG;
//Prototype Functions
void displayAllRaces(DOG dog[], int winners[], int counter, int countOne,
int countTwo, int countThree, int countFour, int countFive, int countSix,
int countSeven, int countEight, int countNine);
void displayMenu();
void getBet(float *bet);
char getChoice();
float getOdds();
void pickDog(DOG dog[], int *counter, int winners[], float *bet, int *countOne,
int *countTwo, int *countThree, int *countFour, int *countFive, int *countSix,
int *countSeven, int *countEight, int *countNine);
main() {
char userChoice;
DOG dog[SIZE];
int counter = 0;
int countOne = 0, countTwo = 0, countThree = 0, countFour = 0,
countFive = 0, countSix = 0, countSeven = 0, countEight = 0,
countNine = 0;
int winners[SIZE] = { 0 };
float bet = 0;
do {
userChoice = getChoice();
switch (userChoice) {
case 'G': // Gamble
getBet(&bet);
pickDog(dog, &counter, winners, &bet, &countOne, &countTwo, &countThree,
&countFour, &countFive, &countSix, &countSeven, &countEight, &countNine);
break;
case 'R': //Results
displayAllRaces(dog, winners,counter, countOne, countTwo, countThree, countFour,
countFive, countSix, countSeven, countEight, countNine);
break;
case 'L': //Leave
printf("\n\tThank you for visiting the Dog Track\n");
break;
default:
printf("\n\tERROR! -- Enter A Valid Selection...\n");
break;
}//End Switch
PAUSE;
} while (userChoice != 'L');
}
void displayAllRaces(DOG dog[], int winners[], int counter, int countOne,
int countTwo, int countThree, int countFour, int countFive, int countSix,
int countSeven, int countEight, int countNine) {
int i = 0;
CLS;
printf("\n\tRace Results: \n");
printf("\tDog\t\t\t\t\tNum of Wins\n");
if (counter > 0) {
printf("\t%s\t\t\t%i\n", dog[0].name, countOne);
printf("\t%s\t\t\t%i\n", dog[1].name, countTwo);
printf("\t%s\t\t%i\n", dog[2].name, countThree);
printf("\t%s\t\t%i\n", dog[3].name, countFour);
printf("\t%s\t\t%i\n", dog[4].name, countFive);
printf("\t%s\t\t%i\n", dog[5].name, countSix);
printf("\t%s\t\t%i\n", dog[6].name, countSeven);
printf("\t%s\t\t\t%i\n", dog[7].name, countEight);
printf("\t%s\t\t\t%i\n", dog[8].name, countNine);
}
else {
printf("\n\t\n");
}
}
void displayMenu(){
CLS;
printf("\n\t==================================================\n");
printf("\n\t== MAIN MENU ==\n");
printf("\n\t==================================================\n");
printf("\n\t[G]amble\n");
printf("\n\t[R]esults\n");
printf("\n\t[L]eave\n");
printf("\n\tEnter Your Selection: ");
}
void getBet(float *bet) {
float result = 0;
printf("\n\tEnter the amount you want to gamble: ");
printf("\n\t(Bet has to be between $1 and $1000)\n");
scanf_s("%f", &result); FLUSH;
if(result < 1 || result > 1000){
printf("\n\tERROR-- Please enter a valid amount\n");
printf("\n\tEnter the amount you want to gamble: ");
printf("\n\t(Bet has to be between $1 and $1000)\n");
scanf_s("%f", &result); FLUSH;
}
printf("\n\tThank you for placing your wager.\n\tGood luck!\n");
*bet = result;
PAUSE;
}
char getChoice() {
char result;
displayMenu();
scanf_s("%c", &result); FLUSH;
result = toupper(result);
return result;
}
float getOdds() {
float odds[9] = { 40, 10, 8, 6, 1, 4, 8, 10, 13 };
return odds[9];
}
void pickDog(DOG dog[], int *counter, int winners[], float *bet, int *countOne,
int *countTwo, int *countThree, int *countFour, int *countFive, int *countSix,
int *countSeven, int *countEight, int *countNine) {
int i = 0;
int choice;
float betMoney = 0;
int winner = 0;
CLS;
printf("\n\tPick a dog from the list:");
strcpy(dog[0].name, "\n\t1.Gandalf the Great");
strcpy(dog[1].name, "\n\t2.Fenrir Greyback");
strcpy(dog[2].name, "\n\t3.Marley the Magnificent");
strcpy(dog[3].name, "\n\t4.Clifford the Big Red Dog");
strcpy(dog[4].name, "\n\t5.Petey the Little Rascal");
strcpy(dog[5].name, "\n\t6.Courage the Cowardly Dog");
strcpy(dog[6].name, "\n\t7.Old Yeller Before the Bullet");
strcpy(dog[7].name, "\n\t8.Pongo the Dalmatian");
strcpy(dog[8].name, "\n\t9.Nymeria Stark\n");
for (i = 0; i < 9; i++) {
printf("%s", dog[i].name);
}
printf("\n");
scanf_s("%i", &choice); FLUSH;
do {
if (choice < 1 || choice > 9) {
printf("\n\tPlease, try again...\n");
scanf_s("%i", &choice);
}
} while (choice < 1 || choice > 9);
betMoney = *bet;
winner = 1 + rand() % (100 - 1 + 1);
if (winner <= 40) {
winner = 1;
(*countOne)++;
}
else if (winner <= 50) {
winner = 2;
(*countTwo)++;
}
else if (winner <= 48) {
winner = 3;
(*countThree)++;
}
else if (winner <= 64) {
winner = 4;
(*countFour)++;
}
else if (winner <= 65) {
winner = 5;
(*countFive)++;
}
else if (winner <= 69) {
winner = 6;
(*countSix)++;
}
else if (winner <= 77) {
winner = 7;
(*countSeven)++;
}
else if (winner <= 87) {
winner = 8;
(*countEight)++;
}
else if (winner <= 100) {
winner = 9;
(*countNine)++;
}
winners[*counter] = winner;
(*counter)++;
if (choice == winner) {
printf("\n\tYou picked a WINNER!\n");
if (winner == 1) {
(*bet) = betMoney * 2;
printf("You win $%.2f\n", *bet);
}
if (winner == 2) {
(*bet) = betMoney * 5;
printf("You win $%.2f\n", *bet);
}
if (winner == 3) {
(*bet) = betMoney * 10;
printf("You win $%.2f\n", *bet);
}
if (winner == 4) {
(*bet) = betMoney * 15;
printf("You win $%.2f\n", *bet);
}
if (winner == 5) {
(*bet) = betMoney * 50;
printf("You win $%.2f\n", *bet);
}
if (winner == 6) {
(*bet) = betMoney * 20;
printf("You win $%.2f\n", *bet);
}
if (winner == 7) {
(*bet) = betMoney * 10;
printf("You win $%.2f\n", *bet);
}
if (winner == 8) {
(*bet) = betMoney * 5;
printf("You win $%.2f\n", *bet);
}
if (winner == 9) {
(*bet) = betMoney * 3;
printf("You win $%.2f\n", *bet);
}
}
else {
printf("\n\tYou picked a LOSER!\n");
(*bet) = (*bet) - betMoney;
}
}
I have included the entire code for my program here (so you can test it if you wish), but only need help in fixing my rand() function. As you can see I want to randomly chose a number between 1-100. If the number is <= 40 then its dog one 40% chance to win, if the number is <= 50 (meaning its <= 50 but >40)then dog 2 wins with a 10% chance to win. I have run the program numerous times and dog 2 always seems to have the most wins after I run it x amount of times. Any help or suggestions would be greatly appreciated!
I have a school assignment to make a hangman game. The game works how I want it to except for one small glitch. If the user entered word is 4 letters or less, the hidden word is displayed with an extra "_\377" at the end. When the user entered word is 5 letters or more, then there is no glitch. I am hoping that someone would be kind enough to help me trouble shoot the problem. Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int letterfinder(char string[], char a, int vari)
{
int length = strlen(string);
int i = vari;
int val = 0;
while( i <= length && val != 1)
{
if( string[i] == a)
{
val = 1;
}
i++;
}
if( val == 0)
{
return 100;
}
else
{
return i;
}
}
int main()
{
char inWord[] = "1111111111111111111111111111";
char outWord2[] = "1111111111111111111111111111";
char guess;
int gameover = 0;
int trys = 10;
int vari = 0;
printf("Please enter a word: ");
gets(inWord);
printf("%s\n", inWord);
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
int i2 = 0;
int j2 = 0;
int i3 = 0;
i2 = strcspn(inWord, outWord2);
char outWord[80];
while(i3 < i2)
{
outWord[i3] = '1';
i3++;
}
while(j2 < i2)
{
outWord[j2] = '-';
j2++;
}
puts(outWord);
while(gameover != 1 )
{
printf("What is your guess: ");
scanf("%s", &guess);
vari = 0;
if(letterfinder(inWord, guess, vari) == 100)
{
printf("Wrong!");
trys--;
printf("You have %d attempts left\n", trys);
if(trys == 0)
{
gameover = 1;
printf("You ran out of attempts. Game over\n");
}
}
else
{
outWord[(letterfinder(inWord, guess, vari) - 1)] = guess;
vari = (letterfinder(inWord, guess, vari));
while(letterfinder(inWord, guess, vari) != 100)
{
outWord[(letterfinder(inWord, guess, vari) - 1)] = guess;
vari = letterfinder(inWord, guess, vari);
}
puts(outWord);
}
int value = 0;
i3 = 0;
while( i3 <= i2)
{
if( outWord[i3] == '-')
{
value = 1;
}
i3++;
}
if(value != 1)
{
printf("Congratulations, you have guessed the word!\n");
gameover = 1;
}
}
return 0;
}
Your code has Undefined Behaviour. In the cases it "works" it is only by chance/luck. char guess; scanf("%s", &guess); That causes memory corruption as you are writing a string to a variable that can only hold a single char. Even a single letter guess will require two characters to store as all C strings are NUL terminated.
– kaylum
User enters command with parameters.There are no errors, but I am having trouble with the weird output.
I took input as string, identified if the input matches the command 'sum', if it does then extracted the parameters in between sum[], stored them in an array and send them as arguments to sum function.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int sumOfArray(int arr[])
{
int sum=0;
for(int i=0;i++;i<sizeof(arr))
{
sum = sum + arr[i];
}
printf("%d\n",sum);
return sum;
}
int main()
{
char input[256];
int j=0,temp=0;
int arraySum[6]={0};
printf("user_account $> ");
fgets(input, sizeof(input), stdin);
if (input[0]=='s' && input[1]=='u' && input[2]=='m')
{
if (input[3]!='(')
{
printf("Please enter proper parameters : sum(num1, num2, ..)\n");
}
else
{
for (int i = 4; i++; input[i] < ']')
{
if (input[i] !=',')
{
if (!isdigit(input[i]))
{
printf("Please enter only digits\n");
break;
}
else
{
temp = int(input[i]);
printf("%d\n",temp);
arraySum[j] = arraySum[j]*10 + temp;
}
}
else j++;
}
}
sumOfArray(arraySum);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sumOfPara(void){
int v, sum = 0;
char ch;
while(1){
if(2 == fscanf(stdin, "%d %c", &v, &ch) && (ch == ',' || ch == ')')){
sum += v;
if(ch == ')')
break;
} else {
fprintf(stderr, "Parameter is invalid.\n");
exit(EXIT_FAILURE);
}
}
return sum;
}
int main(void){
char command[32];
char left_paren;
printf("user_account $> ");
if(2 != fscanf(stdin, "%31[a-z] %c", command, &left_paren) || strcmp(command, "sum") != 0 || left_paren != '('){
fprintf(stderr, "Please enter proper parameters : sum(num1, num2, ..)\n");
exit(EXIT_FAILURE);
} else { //rest
printf("%d\n", sumOfPara());
}
return 0;
}
I have a problem thats giving me a huge ache.
This piece of code purpose is to fill up an array with integer values and at the same time defend against strings and etc....but it doesn't defend against duplicates, but tried I got to far as replacing the number with a new number for example
Enter 6 integers
1, 2, 2, 3, 4, 5
my code will let me replace that 2 at position 1 with another number. What I want it to do is not to repeat the same number again, for example please replace 2 at position 1. I dont want the user to enter 2 again... and I want to make it to double check the work the array if any repeating numbers exists thank you.
system("clear");
printf("\nEntering Winning Tickets....\n");
nanosleep((struct timespec[]){{1, 0}}, NULL);
system("clear");
char userInput[256];
char c;
int duplicationArray[6] = {-1, -1, -1, -1, -1, -1};
for (i = 0; i < 6; i++)
{
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[i], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
for (i = 0; i < 6 - 1; ++i)
{
min = i;
for (j = i+1; j < 6; ++j)
{
if (winningNumbers[j] < winningNumbers[min])
min = j;
}
temp = winningNumbers[i];
winningNumbers[i] = winningNumbers[min];
winningNumbers[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
if (duplicationCounter > -6)
{
for (i = 0; i < 6; i++)
{
int j, min, temp;
min = i;
for (j = i+1; j < 6; ++j)
{
if (duplicationArray[j] > duplicationArray[min])
min = j;
}
temp = duplicationArray[i];
duplicationArray[i] = duplicationArray[min];
duplicationArray[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (duplicationArray[i] == -1)
{
zeroCounter++;
}
}
int resize = (6 - zeroCounter)+1;
for (i = 0; i <= resize; i++)
{
if (duplicationArray[i] == -1)
{
i++;
}
else if (duplicationArray[i] != -1)
{
system("clear");
printf("\nDuplicated numbers has been dected in your array. ");
printf("\nPlease replace the number %d at postion %d with another number: ", winningNumbers[duplicationArray[i]], duplicationArray[i]);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[duplicationArray[i]], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
}
duplicationCounter = 0;
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
printf("%d, ", duplicationCounter);
}
#include <stdio.h>
#include <stdint.h>
#define DATA_SIZE 6
int main(void){
char userInput[256];
int inputNum, winningNumbers[DATA_SIZE];
uint64_t table = 0;
int i=0;
while(i<DATA_SIZE){
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, sizeof(userInput), stdin);
if(sscanf(userInput, "%d", &inputNum) != 1 || inputNum <= 0 || inputNum >= 50)
continue;
uint64_t bit = 1 << inputNum;
if(table & bit)
continue;
table |= bit;
winningNumbers[i++] = inputNum;
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE 6
int inputNumberWithRangeCheck(const char *msg, const char *errMsg, int rangeStart, int rangeEnd){
char inputLine[256];
int n;
for(;;){
printf("%s", msg);
fgets(inputLine, sizeof(inputLine), stdin);
if(sscanf(inputLine, "%d", &n) != 1 || n < rangeStart || n > rangeEnd)
fprintf(stderr, "%s", errMsg);
else
return n;
}
}
int inputNumber(void){
return inputNumberWithRangeCheck(
"\nPlease enter the winning ticket number!(#'s must be between 1-49): ",
"Invalid Input.\n",
1,49);
}
int *inputArray(int *array, size_t size){
int i;
for(i=0;i<size;++i){
printf("\nInput for No.%d\n", i+1);
array[i] = inputNumber();
}
return array;
}
int **duplicateCheck(int *array, size_t size){
int **check, count;
int i, j;
check = malloc(size*sizeof(int*));
if(!check){
perror("memory allocate\n");
exit(-1);
}
//There is no need to sort the case of a small amount of data
//(Cost of this loop because about bubble sort)
for(count=i=0;i<size -1;++i){
for(j=i+1;j<size;++j){
if(array[i] == array[j]){
check[count++] = &array[i];
break;
}
}
}
check[count] = NULL;
if(count)
return check;
else {
free(check);
return NULL;
}
}
int main(void){
int winningNumbers[DATA_SIZE];
int **duplication;
int i, j;
inputArray(winningNumbers, DATA_SIZE);
while(NULL!=(duplication = duplicateCheck(winningNumbers, DATA_SIZE))){
for(i=0;i<DATA_SIZE;++i){
if(duplication[i]){
printf("\nyour input numbers : ");
for(j=0;j<DATA_SIZE;++j)
printf("%d ", winningNumbers[j]);
fprintf(stderr, "\nThere is duplicate. Please re-enter.\n");
*duplication[i] = inputNumber();
} else
break;
}
free(duplication);
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}