This code is for craps .
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <time.h> int roll_dice(void); bool play_game(void); int main() { int i, ch,win = 0,lose = 0; bool flag; srand((unsigned)time(NULL)); do { flag = play_game(); if(flag) { printf("You win!"); win++; } else { printf("You lose!"); lose++; } printf("\n\nPlay again(Y/N)? "); scanf("%c", &ch); ch = getchar(); printf("\n"); }while(ch == 'Y' || ch == 'y'); printf("\nWins: %d Losses: %d",win,lose); return 0; } int roll_dice(void) { return rand()%6 + rand()%6 + 2; } bool play_game(void) { int sum = roll_dice(); printf("You rolled: %d\n", sum); if(sum == 7 || sum == 11) return 1; else if(sum == 2 || sum == 3 || sum == 12) return 0; else { int point = sum; printf("Your point is: %d\n", point); do { sum = roll_dice(); printf("You rolled: %d\n", sum); if(sum == 7) return 0; }while(point != sum); return 1; } }
I only have a problem with a code snippet
printf("\n\nPlay again(Y/N)? "); scanf("%c", &ch); ch = getchar(); printf("\n");
I used because it ends after one iteration with any user input Y or N I thought I was doing it wrong by placing ch = getchar() to eat \n , I deleted it and put a space in front of the conversion specifier and replaced it with " %c" , which also didn't work. When I replaced the conversion specifier with %d works fine.
Is there something wrong with this? I visited this post and it says the same thing as me.
source share