I've looked at questions asked on stackoverflow before, but this is my first time asking, so I apologize in advance for any format mistakes. I've been taking a class on C programming for about a month, and I've been given an assignment to use a do/while loop in my main function to loop a displayMenu(), which allows the user to input either 1, 2, or 3 to display a certain block of information.
int main(void)
{
int option = 0;
do
{
option = displayMenu();
}
while (option == displayName() || displayColor() || displayFood());
}
//Display the menu for choosing an option or exiting the program
int displayMenu()
{
int choice = 1;
while (choice == 1 || 2 || 3)
{
puts("Choose which piece of information you would like to know:");
printf("%s", "1 - My name, 2 - My favorite color, 3 - My favorite food\n");
printf("%s", "Or type in any other number to exit the program: ");
scanf("%d", &choice);
puts("");
if (choice == 1)
displayName();
if (choice == 2)
displayColor();
if (choice == 3)
displayFood();
}
return choice;
}
Now, I'm sure the error is somewhere within these two methods, but just in case, I'm posting the display methods.
//Function to display my name
int displayName()
{
int value = 1;
puts("My name is x.\n");
return value;
}
//Function to display my favorite color
int displayColor()
{
int value = 2;
puts("My favorite color is y.\n");
return value;
}
//Function to display my favorite food
int displayFood()
{
int value = 3;
puts("My favorite food is z.\n");
return value;
}
If the user inputs 1, 2, or 3, the program correctly displays the information and loops to prompt the user again about inputting another value. However, if any other number is input, the program prompts the user again to input a value, when instead it should be closing the program.
What am I doing wrong? I tried inserting a
else return choice;
after the first three if statements, because i thought that would be needed to break the loop, but it didn't work. Does it have something to do with my while conditions? I'm unsure if my conditions are right, (about == and || precedence and whatnot), so if someone could clarify that too it'd be nice.
I know there are probably more efficient methods to executing this program, but I'm limited to what I've been taught in the class, which really isn't anything more than what I've coded.
while (choice == 1 || 2 || 3)
is equivalent to
while ((choice == 1) || 2 || 3)
which is equivalent to
while (1)
What you want is:
while (choice == 1 || choice == 2 || choice == 3)
This line is an infite loop:
while (choice == 1 || 2 || 3)
I guess what you want is:
while (choice == 1 || choice == 2 || choice == 3)
Ignoring the many errors in the original code, what you can do to refactor the loop logic is to use an array of function pointers:
int (*functions[])(void) = { displayName, displayColor, displayFood };
int choice = -1;
do {
choice = get_choice(); // assuming get_choice returns an integer between 0 and 2, or -1 on error/eof.
if (choice != -1)
functions[choice]();
} while (choice != -1)
this will make your code more concise, provided all of your functions have the same prototype.
Well because you got your answer I will not try to give you another Answer which will probably be the same.
One thing you should know, what happens if the user type a letter or a number + a letter (1j) ?
You should have control of your programs when you are dealing with text menus.
Here is a better approach of your program:
#include <stdio.h>
#include <string.h>
int checkInput(int min, int max){
int option,check;
char c;
do{
printf("Choose an Option:\t");
if(scanf("%d%c",&option,&c) == 0 || c != '\n'){
while((check = getchar()) != 0 && check != '\n');
printf("\tThe option has to be between %d and %d\n\n",min,max);
}else if(option < min || option > max){
printf("\tThe option has to be between %d and %d\n\n",min,max);
}else{
break;
}
}while(1);
return option;
}
void quit(void){
printf("Goodbye...\n");
}
//Function to display my name
int displayName(void){
int value = 1;
puts("My name is x.\n");
return value;
}
//Function to display my favorite color
int displayColor(void){
int value = 2;
puts("My favorite color is y.\n");
return value;
}
//Function to display my favorite food
int displayFood(void){
int value = 3;
puts("My favorite food is z.\n");
return value;
}
int displayMenu(void);
int main(void){
int option = 0;
do{
option = displayMenu();
}
while (option != 0);
}
//Display the menu for choosing an option or exiting the program
int displayMenu(void){
int choice;
do{
puts("Choose which piece of information you would like to know:");
printf("%s", "1 - My name\n2 - My favorite color\n3 - My favorite food\n\n");
printf("%s", "Or type in any other number to exit the program: ");
choice = checkInput(0,3);
puts("");
if (choice == 1){
displayName();
}else if (choice == 2){
displayColor();
}else if (choice == 3){
displayFood();
}else if( choice == 0){
quit();
}
}while (choice != 0);
return choice;
}
probably a do{}while(); is better then while{}.
Related
I was writing c program on rock paper and scissor game but could not get the expected result.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
char player[50], choice[10];
puts("Enter your name: ");
gets(player);
int player1 = 0, comp = 0;
for (int i = 0; i < 3; i++)
{
srand(time(NULL));
printf("%s: ", player);
scanf("%s", choice);
int computer = rand()%3;
if (computer == 0){
printf("computer: rock\n");
} else if(computer == 1){
printf("computer: paper\n");
}else{
printf("computer: scissor\n");
}
if (computer == 0 && choice == "paper"){
player1++;
}else if (computer == 0 && choice == "rock"){
continue;
}else if (computer == 0 && choice == "scissor"){
comp++;
}else if (computer == 1 && choice == "paper"){
continue;
}else if (computer == 1 && choice == "rock"){
comp++;
}else if (computer == 1 && choice == "scissor"){
player1++;
}else if (computer == 2 && choice == "paper"){
player1++;
}else if (computer == 2 && choice == "rock"){
comp++;
}else if (computer == 2 && choice == "scissor"){
continue;
}else {
printf("Invalid Entry.");
}
printf("\n");
}
if (player1 > comp){
printf("%s wins.", player);
}else if (player1 == comp) {
printf("%s and computer draws.", player);
}else{
printf("%s loses.", player);
}
return 0;
}
The program works but I am not getting the expecteed result in all 3 runs of the for loop I get only invalid entry as output due to which I can't count the score and the result as both player and comp variable are idle due to this.
output:
Enter your name:
Sam
Sam: rock
computer: scissor
Invalid Entry.
Sam: scissor
computer: scissor
Invalid Entry.
Sam: paper
computer: paper
Invalid Entry.
Sam and computer draws.
I have checked to best my skill and could not find any mistake I don't know why if else-if is acting weirdly, Help me to get correct output and explain me what the problem and where the mistake is.
You need to comare strings using strcmp from <string.h>. Note that strcmp returns 0 if the strings match.
#include <string.h>
int strcmp(const char *str1, const char *str2);
For example you would have to replace choice == "paper" with !strcmp(choise, "paper").
And you should also use fgets instead of gets.
char player[50];
fgets(str, 50, stdin);
Alternatively you could use and scanf (inferior in many cases).
char player[50];
scanf("%49[^\n]", player); /* take \0 into account */
I am making a tic tac toe game in which the user competes against the computer. Whenever the person chooses a spot between 1 and 9, the computer needs to choose one too. For this, I am using rand(). However, if the spot is already taken, I need the computer to calculate a new one. I've tried using while and do-while loops but when I apply them, cmd stops working and doesn't let me continue the game.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct symbol{
int marcado;
char simbolo;
} SPOT;
SPOT casilla1 = {0,'1'};
SPOT casilla2 = {0,'2'};
SPOT casilla3 = {0,'3'};
void table();
void User();
void AI();
int main(){
system("cls");
User();
AI();
Check();
return 0;
}
void table(){
printf("\n %c | %c | %c ",spot1.symbol,spot2.symbol,spot3.symbol);
}
this is the function in which the user chooses a spot:
void User(){
char choice;
do{
do{
board();
printf("\n\nChoose a spot: ");
fflush(stdin);
scanf("%c",&choice);
}while(choice < '1' || choice > '3');
switch(choice){
case '1': if(choice == '1'){
system("cls");
if(casilla1.marcado == 1){
printf("\noccupied\n");
}
else if(casilla1.marcado == 0){
casilla1.marcado = 1;
casilla1.simbolo = 'X';
AI();
}
}
break;
case '2': if(choice == '2'){
system("cls");
if(casilla2.marcado == 1){
printf("\noccupied\n");
}
else if(casilla2.marcado == 0){
casilla2.marcado = 1;
casilla2.simbolo = 'X';
AI();
}
}
break;
case '3': if(choice == '3'){
system("cls");
if(casilla3.marcado == 1){
printf("\noccupied");
}
else if(casilla3.marcado == 0){
casilla3.marcado = 1;
casilla3.simbolo = 'X';
AI();
}
}
break;
}while(Check() != 0 && Check() != 1);
}
and this is the function for the computer. In which I am having trouble in the 'else if' statements since I don't know what to put in them.
void AI(){
int random;
srand(time(NULL));
random = rand() % 3 + 1;
if (random == 1){
if(casilla1.marcado == 0){
casilla1.simbolo = 'O';
casilla1.marcado = 1;
}
else if(casilla1.marcado == 1){
random = rand() % 3 + 1
}
}
if (random == 2){
if(casilla2.marcado == 0){
casilla2.simbolo = 'O';
casilla2.marcado = 1;
}
else if(casilla2.marcado == 1){
random = rand() % 3 + 1;
}
}
if (random == 3){
if(casilla3.marcado == 0){
casilla3.simbolo = 'O';
casilla3.marcado = 1;
}
else if(casilla3.marcado == 1){
random = rand() % 3 + 1;
}
}
}
As I said before, I've tried putting the whole AI() inside the different types of loops, putting only rand() inside them, and so on, and still can't get it to work.
First, choose your data structures better. Instead of:
SPOT casilla1 = {0,'1'};
SPOT casilla2 = {0,'2'};
SPOT casilla3 = {0,'3'};
use
SPOT casilla[3] = { {0,'1'}, {0,'2'}, {0,'3'} };
As a consequence, the switch constructs are not needed any longer. Instead of:
if(casilla1.marcado == 0){
if(casilla2.marcado == 0){
if(casilla3.marcado == 0){
use:
if(casilla[random-1].marcado == 0){
the person chooses a spot between 1 and 9
and
random = rand() % 9 + 1;
You only have 3 casilla. Where are the other 6?
I've tried using while and do-while loops
In AI() there are no loops. Maybe you can show us a code with loops?
printf("\n\nChoose a spot: ");
fflush(stdin);
You probably wanted to fflush() stdout?
this is both my first time asking a question and also one of my first times writting such a big programm. As you might guess im new at programming.
Alright the source code:
#include <stdio.h>
typedef struct{
int **a;
int size;
}_board;
typedef _board* board;
typedef struct{
int row,col;
}position;
int main () {
int i, j, turn=1, victory = 0, num=0;
_board b;
char P1symbol, P2symbol, mark, boardarray[b.size][b.size];
position p;
printf("WELCOME TO THE GAME OF TIC TAC TOE!\n");
do {
printf("\nwill player one, use X or O as his symbols? select by pressing x or o\n");
scanf(" %c", &P1symbol);
if (P1symbol == 'x' || P1symbol == 'o') {
num = 1;
}
} while ( num == 0);
if (P1symbol == 'x') {
P2symbol = "o";
}
else {
P2symbol = "x";
}
do {
printf("\n now choose the size of the game board, type a numeral and press enter");
scanf("%d", &b.size);
}while (b.size <= 0);
for (i=0; i=b.size; i++){
for (j=0; j=b.size; j++){
boardarray[i][j] = "-";
}
}
do {
do {
boardsketch(boardarray, b.size);
if (turn%2 == 1) {
printf("player 1, please choose a box to input you mark on");
mark = P1symbol;
}else{
printf("player 2, please choose a box to input you mark on");
mark = P2symbol;
}
printf("type the coordinates i,j, which correspond to the row and collumn number");
printf("make sure the numbers are valid, not taken, and between 0 and %d", b.size);
scanf("%d %d", &p.row, &p.col);
}while (p.row > b.size && p.row < 0 && p.col > b.size && p.col <0 && boardarray[p.row][p.row] != "-");
turn++;
boardarray[p.row][p.col] = mark;
} while (wincheck(boardarray, p.row, p.col, b.size) != 1);
return 0;
}
int wincheck(int row, int col, int size, char boardarray[size][size])
{
if (boardarray[row][col] = boardarray[row -1][col -1] = boardarray[row +1][col +1]) {
return 1;
}
if (boardarray[row][col] = boardarray[row -1][col] = boardarray[row +1][col]) {
return 1;
}
if (boardarray[row][col] = boardarray[row][col -1] = boardarray[row][col +1]){
return 1;
}
if (boardarray[row][col] = boardarray[row -1][col +1] = boardarray[row +1][col -1]){
return 1;
}
}
void boardsketch(int size, char boardarray[size][size]) {
int i, j;
for (i=0; i=size; i++) {
for (j=0; j=size; j++) {
if (boardarray[i][j] == '-') {
printf("| ");
} else {
printf("%c |", &boardarray[i][j]);
}
}
}
}
Now the program's purpose is to simulate a game of tic tac toe (with the addition of the user, deciding the size of the game board). My problem is that, altough compilation IS achieved the program does 2 wierd behaviors when reaching a specific line, that line being:
do {
printf("\n now choose the size of the game board, type a numeral and press enter");
scanf("%d", &b.size);
}while (b.size <= 0);
If i input a value that doesnt obey to b.size <= 0, the printf above, repeats indefinately, if i DO put a correct value, the programm doesnt resume. What am i doing wrong? again im new at programming sooooo... go easy on me :D
There are compiler errors in your code. I don't know how you got it to compile and build it the first place.
Compiler errors:
You have:
P2symbol = "o";
Type of "o" is char const*. The type of P2symbol is char. What you need is
P2symbol = `o`;
Few lines after that, you have:
P2symbol = "x";
That needs to be changed to:
P2symbol = `x`;
Few lines after that, you have:
boardarray[i][j] = "-";
It suffers from the same compiler error. You need to change it to:
boardarray[i][j] = `-`;
Your declaration and definition of boardsketch does not match with the way you are calling it. Your call is:
boardsketch(boardarray, b.size);
You have defined it as:
void boardsketch(int size, char boardarray[size][size]) {
....
}
You need to change either the call or the function definition so that they match. Also, you should declare the function before it is used. Add
void boardsketch(int size, char boardarray[size][size]);
before the start of main.
The definition and call of wincheck suffers from the same error. It also should have a declaration before it's usage.
A few lines after that call to boardarray, you have the line:
}while (p.row > b.size && p.row < 0 && p.col > b.size && p.col <0 && boardarray[p.row][p.row] != "-");
The last part of that statement suffers from the char and char const* mismatch. You need to change it to:
}while (p.row > b.size && p.row < 0 && p.col > b.size && p.col <0 && boardarray[p.row][p.row] != '-');
Run Time Errors:
You have:
_board b;
char P1symbol, P2symbol, mark, boardarray[b.size][b.size];
The problem with that is b.size is not initialized. It could be anything. Using it to declare broadarray is problem. Imagine the chaos that will ensue if the b.size were to be initialized to a negative number. For sane and predictable behavior, you should initialize b properly before using its data.
A few lines below, you are asking for size to be input by the user.
do {
printf("\n now choose the size of the game board, type a numeral and press enter");
scanf("%d", &b.size);
}while (b.size <= 0);
There is a logic error here. You are asking for the size of the board after you have already created boardarray. What you could do is gather the initial input and use them to call another function where the core of the game play happens.
/* Function that contains the core part of playing the game */
void playgame(char P1symbol, char P2symbol, int size)
{
int i, j, turn=1, victory = 0;
char mark, boardarray[size][size];
position p;
for (i=0; i=size; i++){
for (j=0; j=size; j++){
boardarray[i][j] = '-';
}
}
do {
do {
boardsketch(size, boardarray);
if (turn%2 == 1) {
printf("player 1, please choose a box to input you mark on");
mark = P1symbol;
}else{
printf("player 2, please choose a box to input you mark on");
mark = P2symbol;
}
printf("type the coordinates i,j, which correspond to the row and collumn number");
printf("make sure the numbers are valid, not taken, and between 0 and %d", size);
scanf("%d %d", &p.row, &p.col);
}while (p.row > size && p.row < 0 && p.col > size && p.col <0 && boardarray[p.row][p.row] != '-');
turn++;
boardarray[p.row][p.col] = mark;
} while (wincheck(p.row, p.col, size, boardarray) != 1);
}
Now, main can be simplified to:
int main () {
char P1symbol;
char P2symbol;
int size;
int num = 0;
printf("WELCOME TO THE GAME OF TIC TAC TOE!\n");
do {
printf("\nwill player one, use X or O as his symbols? select by pressing x or o\n");
scanf(" %c", &P1symbol);
if (P1symbol == 'x' || P1symbol == 'o') {
num = 1;
}
} while ( num == 0);
if (P1symbol == 'x') {
P2symbol = 'o';
}
else {
P2symbol = 'x';
}
do {
printf("\n now choose the size of the game board, type a numeral and press enter");
scanf("%d", &size);
}while (size <= 0);
playgame(P1symbol, P2symbol, size);
return 0;
}
Ah, the problem is your for loop after the do while. You are assigning your counters instead of evaluating the limits. Asigning them will result to true every time. Try this instead:
for (i=0; i<b.size; i++){
for (j=0; j<b.size; j++){
boardarray[i][j] = "-";
}
}
Also, do not create an array with undefine value b.size...
typedef struct contact {
char firstname [40];
char lastname [40];
char address [100];
char phone[10];
}contact;
int main ()
{
FILE *pFile;
contact entry = {"", "", "", ""};
int choice;
char cont = 5;
pFile = fopen("C:\\contacts.txt", "w+");
if(!pFile){
printf("File could not be open");
return 1;
}
printf("Choose a selection\n\n");
printf("1. Enter First Name\n");
printf("2. Enter Last Name\n");
printf("3. Enter Address\n");
printf("4. Enter Phone Number\n\n");
scanf( "%d", &choice);
while (choice = 1|2|3|4|cont){
if (choice = 1){
printf ("First name: ");
fgets(entry.firstname, sizeof(entry.firstname),stdin);
}
else if(choice = 2){
printf ("Last name: ");
fgets(entry.lastname, sizeof(entry.lastname),stdin);
}
else if(choice = 3){
printf ("Address: ");
fgets(entry.address, sizeof(entry.address),stdin);
}
else if (choice = 4){
printf ("Phone number: ");
fgets(entry.phone, sizeof(entry.phone),stdin);
}
else
printf("Exiting");
break;
fwrite (&entry, sizeof (struct contact), 1, pFile);
printf ("Would you like to enter a new contact? (y/n)");
scanf ("%d", &cont);
if (cont = 'n'|'N')
return 0;
}
fclose(pFile);
getchar();
return 0;
}
is my code at the moment. Each time I give any option 1,2,3,4, put in a entry and press enter the window closes. I'm unsure if the logic makes sense and any suggestions are welcome but it "seems" okay to me but obviously I need another set of eyes. I want it where I don't have to enter all entries for every person I put in the file. Also, to note, I initially cont to 5 just because it was complaining.. bad practice I know. Any helpful information is appreciated
Your program ends because the break; isn't in the scope you think it is:
else if (choice = 4){
printf ("Phone number: ");
fgets(entry.phone, sizeof(entry.phone),stdin);
}
else
printf("Exiting");
break;
Even though you've indented the break, it doesn't belong to the else clause. So no matter what happens in the if/else block, the break gets executed and your program breaks out of the loop and ends.
To fix it, add braces to enclose the break inside the scope of the else.:
else if (choice = 4){
printf ("Phone number: ");
fgets(entry.phone, sizeof(entry.phone),stdin);
}
else
{
printf("Exiting");
break;
}
And once you fix that, this line will cause your program to terminate because it always evaluates to true and returns from main:
if (cont = 'n'|'N')
return 0;
You want that line to say
if (cont == 'n' || cont == 'N')
return 0;
These fixes will at least stop your program from terminating, but as others have pointed out there are numerous logical errors elsewhere that will prevent it from doing what you want.
For example, the following line:
while (choice = 1|2|3|4|cont){
belies a misunderstanding of some fundamental concepts.
First = is the assignment operator. The above code, among other things, changes the value of choice. Use == for equality comparison.
Second, the | operator is a bitwise or. The value of 1|2|3|4|5 is 7 (I'll leave it to you to figure out why sometime). Instead, use || like this:
while (choice == 1 || choice == 2 || choice == 3 || choice == 4 || choice == cont) {
There are other similar errors throughout your code.
A single = does assignment in C. if (a = 5) { /* always executed! */ } sets a to 5 and then executes the if-branch because a = 5 evaluates to 5 which is considered true.
You want == which compares values. Thus:
if (choice = 1){
Should be
if (choice == 1){
Another thing:
while (choice = 1|2|3|4|cont){
Does not do what you think it does. It's actually computing the bitwise or of 1, 2, 3, 4 and cont. (So just changing = to == wouldn't be sufficient.) You need to compare each value in turn:
while (choice == 1 || choice == 2 || choice == 3 || choice == 4 || choice == cont){
Also notice the use of || (logical OR) instead of bitwise or.
EDIT: The reason your program prematurely exits is because of the following:
else
printf("Exiting");
break;
You're missing curly braces ({ and }), so it actually means the following (despite misleading indention):
else
printf("Exiting");
break;
Your code probably has more errors.
By using if (choice = 1) you are saying "If I change choice to 1" which is virtually guaranteed to work, but it destroys the previous value choice held.
You want to start off with if (choice == 1) which means "If I compare choice to 2, is this equal?`.
wiHi everyone since last time i found extreme help on here, im gonna ask a question again
My code doesnt return right values :
something is wrong in the play_game function and i cant figure out what it is.I believe that all cases are covered but somehow they end up messed up.
also the code doesnt loop for everytime i want to play a game after the second game it stops.
this is not an assignment
any suggestion?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
static int sum, point, win = 0, roll = 0;
bool play_game(void);
int roll_dice(void);
int main(void){
srand(time(NULL));
play_game();
char input[10];
do{ point = 0;
play_game();
if(win == 1){ // I'm assuming that play returns whether you won or not
printf("You won!\n");
}else{
printf("You lost!\n");
}
printf("Would you like to continue? y/n\n");
gets(input);
}while(*input == 'y'); // gets() flushes the buffer for next time you need input
return 0;
}
bool play_game(void){
point=0;
roll_dice();
printf("Your point is %d\n", sum);
while(roll == 1) /* first round */
{
if(sum == 7 || sum == 11)
return win = 1;
else if(sum == 2 || sum == 3 || sum == 12)
return win = 0;
else if(sum == 1 || sum == 4 || sum == 5 || sum == 6 || sum == 8 || sum == 9 || sum == 10){
point=sum;
roll_dice();
}
}
while(roll > 1) /* all others rounds*/
{
if(sum == 7)
return win = 0;
else if(sum == point)
return win = 1;
else if(sum != point || sum != 7)
roll_dice();
}
}
int roll_dice(void){
int a,b;
a=1+rand() % (6);
b=1+rand() % (6);
sum=a+b;
roll++;
printf("You rolled %d\n", sum);
return sum;
}
OUTPUT
A couple of points:
You probably want 1 + rand() % 6
The return value of printf() is probably not what you want to return from roll_dice()
The loop needs to be more like:
main(){
char input[10];
do{
score = 0; //Always initialize the score
if(play_game()){ // I'm assuming that play returns whether you won or not
printf("You won!\n");
}else{
printf("You lost!\n");
}
printf("Would you like to continue? y/n\n");
gets_s(input, 9);
}while(*input == 'y'); // gets() flushes the buffer for next time you need input
}
Kyle's answer is just fine (as I see it), But I can spot a few problems, hope it'll help you in further cases.
You always win, and I know it's nice, but I bet it's not the expected behavior:
while(true) // This will always happen, because true is always evaluated as true
{
printf("Won\n\n");
printf("Play again? y/n: ");
break;
}
while(false) //This will never happen, since false is always evaluated as false
{
printf("Lost\n\n");
printf("Play again? y/n: ");
break;
}
I think you meant to check the result of play_game(). So add another variable and check against it:
bool win;
win = play_game();
while (win == true)
...
while (win == false)
...
Why using while loop there? you break it in the first iteration anyway
if(win == true)
{
printf("Won\n\n");
}
else
{
printf("Lost\n\n");
}
printf("Play again? y/n: ");
The game will run not more than twice, because you don't have a loop that depends on the answer, but only an if statement that is evaluated just one time:
if(v=getchar() == 'y') //This is the second time the code runs, after that? nada.
{
point =0; /* reset point var */
play_game();
}
else if(v=getchar() == 'n') // Why adding this check? you're going out anyway after the if-else
exit(1);
EDIT
When you use a while loop, what you do is saying:
While (some expression in the parenthesis) is true, execute the code in the block {..} and then check again the expression in parenthesis.
If you write while(true), you actually writing while true is true, execute the code in the block. And this will always happen.
If you write while(false) you actually write while false is true, execute the code in the block. and this false is never true, than it will never execute the code in the block.
If you want a real condition here, you can use while(play_game()). this is like writing, while the returned value from the function play_game is true, execute the code in the block and then the code will be executed only when the play_game function return true (which indicates a win in the game).
There are many good C tutorials out there, start here or here
It is hard to tell from your description (please say what you expected to happen, and what happened instead), but the first thing I notice is that you are rolling 5-sided dice for a and b.
Rolling of the dice is happening at at incorrect points during your game sequence.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
// add defines to make states easier to read
#define WIN 1
#define LOSE 0
static int sum, point, win = 0, roll = 0;
//bool play_game(void);
int play_game(void); // changed return type to be int
int roll_dice(void);
int main(void){
srand(time(NULL));
// play_game(); // unncessary
char input[10];
do
{
point = 0;
//play_game();
// if(win == 1){
if(play_game()){ // use return value from play_game()
printf("You won!\n");
}else{
printf("You lost!\n");
}
printf("Would you like to continue? y/n\n");
// gets(input);
fgets(input, sizeof(input), stdin); // a safer input read
} while(*input == 'y'); // gets() flushes the buffer for next time you need input
return 0;
}
// bool play_game(void)
int play_game(void) // changed return type to be int
{
point=0;
// remove as this messes up the roll sequence.
// roll_dice();
// incorrect place to display this message
//printf("Your point is %d\n", sum);
// the while loop here is unnecessary
//while(roll == 1) /* first round */
//{
roll_dice(); // add for initial come out roll.
if(sum == 7 || sum == 11) { // I use braces to remove ambiguity
// return win = 1;
return WIN;
} else if(sum == 2 || sum == 3 || sum == 12) {
//return win = 0;
return LOSE;
}
// sum will never be 1
// on that note if it control reaches here it will be one of the other numbers.
//} else if(sum == 1 || sum == 4 || sum == 5 || sum == 6 || sum == 8 || sum == 9 || sum == 10){
// point=sum;
// roll_dice(); // remove as this messes up the roll sequence.
// }
point=sum;
printf("Your point is %d\n", sum);
//}
// while(roll > 1) /* all others rounds*/
while (1) // might as well loop forever
{
roll_dice(); // add for subsequent dice rolls
if(sum == 7) {
//return win = 0;
return LOSE;
} else if(sum == point) {
// return win = 1;
return WIN;
}
// remove as this is unnecessary
// else if(sum != point || sum != 7)
// remove as this messes up the roll sequence.
//roll_dice();
}
}
int roll_dice(void){
int a,b;
a=1+rand() % (6);
b=1+rand() % (6);
sum=a+b;
// roll++; // unncessary
printf("You rolled %d\n", sum);
return sum;
}