If, else & while bug (not activating / activating twice) - c

I'm having this problem in where when the player choose to attack. It won't print anything at first but will only print when the player hits the knight. Something else is also if the player chooses an invalid choice in gender, the first mistake will print once but if the mistake happen again it will print twice. I would appreciate any help, just doing my lil' project.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
int main()
{
char enter = 0;
char pNAME[30];
char pGENDER;
char pWEAPON[20];
char pARMOR [10];
int pWEAPONID;
int choice1,choice2 = 0,choice3;
int pAGE;
int pATK = 0;
int pHP = 30;
int pATKS = 10;
int pATKC = 0;
int knightHP = 25;
int knightATKS = 20;
int knightATKC;
int kingHP = 30;
int kingATKC;
srand((unsigned)time(NULL));
printf("While you are enjoying your breakfast at your house, suddenly you get teleported to a different dimension and no one to be seen except an old man.\n");
printf("\nOld Man: What is your name warrior?\n");
printf("\nInsert name:");
scanf("%s",pNAME);
fpurge( stdin );
printf("\nInsert gender (m/f):");
scanf("%c",&pGENDER);
fpurge( stdin );
while ( pGENDER != 'f' &&pGENDER != 'm' )
{
printf("\nInvalid entry, please try again.\n");
printf("\nInsert gender (m/f):");
scanf("%c",&pGENDER);
}
printf("\nOld Man: Now how old are you warrior?\n");
printf("\nInsert Age:");
scanf("%d",&pAGE);
fpurge( stdin );
if ( pAGE < 18)
{
printf("\nOy mate! No stalker!\n");
printf("\nTeleporting back to reality...\n");
return 0;
}
if ( pAGE > 80)
{
printf("\nNo oldies allowed!\n");
printf("\nTeleporting back to reality...\n");
return 0;
}
printf("\nOld Man: Welcome warrior I fear the knights has taken over our kingdom, and you, %s, are the only one who can save us.\n",pNAME);
printf("\n%s: How am I suppose to do that?[Enter]\n",pNAME);
while (enter != '\r' && enter != '\n') { enter = getchar(); }
printf("Old Man: Pick one of these three items\n");
printf("\n[1] Axe : Damage = 7\t Accuracy = 70%% Critical = 7%%\n"); //
printf("\n[2] Sword : Damage = 5\t Accuracy = 77%% Critical = 8%%\n");
printf("\n[3] Knife : Damage = 3\t Accuracy = 83%% Critical = 9%%\n");
printf("\nYou choose: ");
scanf("%d",&pWEAPONID);
if (pWEAPONID == 1)
{
pATK = 8;
pATKS = 14; // 10/14 chance
strcpy(pWEAPON, "Axe");
}
if (pWEAPONID == 2)
{
pATK = 6;
pATKS = 14; // 10/13 chance
strcpy(pWEAPON, "Sword");
}
if (pWEAPONID == 3)
{
pATK = 4;
pATKS = 12; // 10/12 chance
strcpy(pWEAPON, "Knife");
}
if (pWEAPONID > 3)
{
printf("\nYou are gonna be fighting with your bare fist");
pATK = 2;
pATKS = 11; // 10/11 chance
strcpy(pWEAPON, "Fist");
}
printf("\nOld Man: Good choice, you chose the %s, now continue foward to destroy The Evil King\n",pWEAPON);
printf("\nWhile you are continuing your journey to destroy The Evil King, you come face to face with a knight\n");
printf("\nWhat do you want to do?\n");
printf("\n[1] Run [2] Battle:");
scanf("%d",&choice1);
if (choice1 == 1) //Dead
{
printf("\nYou attempted to run, but the knight chases you with his horse and a spear.\n");
printf("\nThe knight stabs you right through your body.\n");
printf("\nYou are dead, thanks for playing.\n");
return 0;
}
while (pHP != 0 && knightHP != 0) // Combat starts
{
knightATKC = rand()%knightATKS; // 15/20 chance
sleep(1);
// Knight's turn
if ( knightATKC == 1 || knightATKC == 2 || knightATKC == 3 || knightATKC == 4 || knightATKC == 5 || knightATKC == 6 || knightATKC == 7 || knightATKC == 8 || knightATKC == 9 || knightATKC == 10 || knightATKC == 11 || knightATKC == 0 )
{
printf("\nThe knight swings his spear at %s\n",pNAME);
printf("The knight hits %s for 4 HP\n",pNAME);
pHP = pHP - 4;
printf("%s has %d/30 HP\n",pNAME,pHP);
if (pHP == 0 || pHP <0)
{
printf("\nYou fell to the ground heavily damages, while the knight lungs at your for the final hit\n");
printf("\nYou are dead, thanks for playing.\n");
return 0;
}
printf("\nWhat do you want to do?\n");
printf("[1] Attack [2] Charge your attack [3] Heal:"); // Charge and Heal not activated yet
scanf("%d",&choice1);
}
else if (knightATKC == 12 || knightATKC == 13 )
{
printf("\nThe knight slashes his spear at %s\n",pNAME);
printf("The knight critically hit %s for 6 HP\n",pNAME);
pHP = pHP - 6;
printf("%s has %d/30 HP\n",pNAME,pHP);
if (pHP == 0 || pHP <0)
{
printf("\nYou fell to the ground heavily damages, while the knight lungs at your for the final hit\n");
printf("\nYou are dead, thanks for playing.\n");
return 0;
}
printf("\nWhat do you want to do?\n");
printf("[1] Attack [2] Charge your attack [3] Heal:"); // Charge and Heal not activated yet
scanf("%d",&choice2);
}
else if (knightATKC == 14)
{
printf("\nThe knight's horse kicks %s\n",pNAME);
printf("The knight's horse hit %s for 8 HP\n",pNAME);
pHP = pHP - 8;
printf("%s has %d/30 HP\n",pNAME,pHP);
if (pHP == 0 || pHP <0)
{
printf("\nYou fell to the ground heavily damages, while the knight lungs at your for the final hit\n");
printf("\nYou are dead, thanks for playing.\n");
return 0;
}
printf("\nWhat do you want to do?\n");
printf("[1] Attack [2] Charge your attack [3] Heal:");
scanf("%d",&choice2);
}
else
{
printf("\nThe knight swings his spear at %s\n",pNAME);
printf("You blocked his spear with your %s\n",pWEAPON);
printf("%s has %d/30 HP\n",pNAME,pHP);
printf("\nWhat do you want to do?\n");
printf("[1] Attack [2] Charge your attack [3] Heal:"); // Charge and Heal not activated yet
scanf("%d",&choice2);
}
// Player's turns
if (choice2 == 1)
{
pATKC = rand()%pATKS;
if (pATKC == 0 || pATKC == 1 || pATKC == 2 || pATKC == 3 || pATKC == 4 || pATKC == 5 || pATKC == 6 || pATKC == 7 || pATKC == 8 || pATKC == 9)
{
printf("\nYou swing your %s at the knight\n",pWEAPON);
printf("You hit the knight with your %d\n",pATK);
knightHP = knightHP - pATK;
printf("The knight has %d/25\n",knightHP);
if (knightHP == 0 || knightHP <0)
{
printf("\nYou fell to the ground heavily damages, while the knight lungs at your for the final hit\n");
printf("\nYou are dead, thanks for playing.\n");
}
printf("\nWhat do you want to do?\n");
printf("[1] Run [2] Attempt to block\n");
scanf("%d",&choice3);
}
else if (pATKC == 10)
{
printf("\nYou swing your %s at the knight\n",pWEAPON);
printf("You critically hit the knight for %f\n",pATK * 1.5);
knightHP = knightHP - (pATK * 1.5);
printf("The knight has %d/25\n",knightHP);
printf("\nWhat do you want to do?\n");
printf("[1] Run [2] Attempt to block\n");
scanf("%d",&choice3);
}
else
{
printf("\nYou swing your %s at the knight\n",pWEAPON);
printf("The knight intercept your %s with his spear\n",pWEAPON);
printf("The knight has %d/25\n",knightHP);
printf("\nWhat do you want to do?\n");
printf("[1] Run [2] Attempt to block\n"); // Not activated yet
scanf("%d",&choice3);
}
}
}

the posted code does not compile, so it certainly does not run.
here are a few of the many listed problems with the code
Always enable all warnings when compiling.
For gcc, at a minimum use: -Wall -Wextra -pedantic
line:column: message
35:5: warning implicit declaration of function `fpurge`
224:5: error: expected declaration or statement at end of input
27:9: warning: unused variable `kingATKC`
26:9: warning: unused variable `kingHP`
15:10: warning: unused variable `pARMOR`
BTW: fpurge is not a supported function in the stdio.h header file
Suggest, rather than calling fpurge(), use:
while( '\n' != getchar() );
when calling scanf(), always check the returned value, not the parameter value, to assure the operation was successful
when inputting the 'gender', apply tolower to the value so user could enter either upper or lower case
this code: around line 232 is killing the hero when it should be killing the knight
if (knightHP == 0 || knightHP <0)
{
printf("\nYou fell to the ground heavily damages, while the knight lungs at your for the final hit\n");
printf("\nYou are dead, thanks for playing.\n");
}
upon any death, the resulting HP can be less than 0 however this line:
while (pHP != 0 && knightHP != 0) // Combat starts
only terminates the loop if HP == 0 it should be:
while (pHP > 0 && knightHP > 0) // Combat starts
Suggest, for a combat sequence, that there is only one place where the hero can input a decision about what they want to do next.
Suggest, make each combat activity a separate sub function.
The above two suggestions will greatly increase the simplicity of each function and make the code much easier to debug.

Related

RockPaperScissor game not getting expected result - C programming

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 */

Why is my program skipping my first loop?

I am working on an assignment in C, trying to create a program that simulates a "Rock, Paper, Scissors" match between the user and the computer. Everything is working fine except the for loop I have created is skipping the first iteration of the loop and going straight to my second match. Is there any way to fix this? Code and compilation below
main.c
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
int main(void) {
srand(time(0)); // This gives the random function a new seedallows me to use time in order to create "random" numbers. //
time_t t; // Allows the program to store system time values. //
int R; // This statement declares the variable for the move "Rock". //
int P; // This statement declares the variable for the move "Paper". //
int S; // This statement declares the variable for the move "Scissors". //
int numMatches; // This statement declares the variable for the number of matches that are to be played. //
int roundNumber; // This statement declares the variable for the current round of the match that is being played. //
int compMove; // This statement declares the variable that represents the move (rock, paper, or scissors) that the computer makes. //
char userMove; // This statement declares the variable that represents the move (rock, paper, or scissors) that the user of the program chooses. //
int randNumber; // This statement declares the variable for the random number that will be generated. //
printf("Starting the Rock, Paper, Scissors Game!\n");
printf("Enter the number of matches to play: ");
scanf(" %d", &numMatches); // This statement allows the user to input the number of matches he/she wishes to play. //
for (roundNumber = 1; roundNumber <= numMatches; roundNumber++) { // This for statement first initializes the number of rounds to 1. Then, the statement sets a parameter that the for loop will only continue as long as the number of matches completed is less that than the total matches that are to played. The last statement increments
printf("\nMatch %d: Enter R for rock, P for paper, or S for scissors: ", roundNumber);
fflush(stdin);
userMove = getchar();
randNumber = (rand() % 3) + 1; //1 to 3//
compMove = randNumber == 0 ? 'R' : randNumber == 1 ? 'P' : 'S';
if ((userMove == 'R') && (compMove == 'S')) { // These statements state the result of the game depending on the user's move and the computer's move. //
printf("The computer chose scissors. You won \n");
} else
if ((userMove == 'P') && (compMove == 'R')) {
printf("The computer chose rock. You won \n");
} else
if ((userMove == 'S') && (compMove == 'P')) {
printf("The computer chose paper. You won \n");
} else
if ((userMove == 'R') && (compMove == 'R')) {
printf("The computer chose rock. You tied \n");
} else
if ((userMove == 'P') && (compMove == 'P')) {
printf("The computer chose paper. You tied \n");
} else
if ((userMove == 'S') && (compMove == 'S')) {
printf("The computer chose scissors. You tied \n");
} else
if ((userMove == 'R') && (compMove == 'P')) {
printf("The computer chose paper. You lose \n");
} else
if ((userMove == 'P') && (compMove == 'S')) {
printf("The computer chose scissors. You lose \n");
} else
if ((userMove == 'S') && (compMove == 'R')) {
printf("The computer chose rock. You lose \n");
}
}
return 0;
}
compile
The line:
userMove = getchar();
Catches the char but lets a newline character \n in the buffer caused by pressing Enter, you need to discard it.
You can do, for instance, this:
userMove = getchar();
getchar(); // <-- catches and discards '\n'
I would also get rid of fflush(stdin), it causes undefined behaviour, reasons in Why should I use fflush(stdin) in this program?.
Replace it also with getchar(). Or use type specifier with discard in your scanf function like scanf(" %d%*c", &numMatches);
Here is a working sample
Another thing that is not very good is the fact that none these variables is being used:
time_t t; // Allows the program to store system time values. //
int R; // This statement declares the variable for the move "Rock". //
int P; // This statement declares the variable for the move "Paper". //
int S; // This statement declares the variable for the move "Scissors". //

C | Comparison between two groups of arrays

I'm pretty fresh in the computers world and started to work on c.
now i'm building a little project about generating code (shown below):
My main:
#include <stdio.h>
#include "connect.h"
#define EASY 20
#define NORMAL 15
#define HARD 10
#define CRAZY 30
int main ()
{
int choice = 1;
char enter, returnV;
system("cls");
printf("Welcome to ""THE MAGSHIMIM CODE BREAKER""!!!\n");
printf("\n");
printf("A secret password was chosen to protect the credit card of Pancratius,\nthe descendant of Antiochus\n");
printf("Your mission is to stop Pancratius by revealing his secret password.\n");
printf("the rules are the follows:\n");
printf("\n");
printf("1. In each round you try to guess the secret password (4 distinct digits)\n");
printf("2. After every guess you'll receive two hints about the password");
printf("\nHITS the number of digits in your guess witch were exactly right.\n");
printf("MISSES the number of digits in your guess witch belong to the password but weremiss-placed\n");
printf("3 - if you'll fail to guess the password after a certain number of rounds \tPancratius will buy all the gift to Hanukkah!!!\n");
printf("\n");
printf("Press Enter to continue...\n");
enter = getch();
if (enter = '\n'){
do{
system("cls");
printf("please choose level:\n");
printf("1 - easy (20 rounds)\n");
printf("2 - normal (15 rounds)\n");
printf("3 - hard (10 rounds)\n");
printf("4 - crazy (random number of rounds 5-25)\n");
printf("Make a choice:");
_flushall();
scanf("%1d",&choice);
if (choice == 1 || choice == 2 || choice == 3 || choice == 4 ){
switch(choice){
case (1):
system("cls");
returnV = levels(EASY);
break;
case (2):
system("cls");
returnV = levels(NORMAL);
break;
case (3):
system("cls");
returnV = levels(HARD);
break;
case (4):
system("cls");
returnV = levels(CRAZY);
break;
switch(returnV){
case('y'):
break;
case('n'):
return 0;
break;
}
}
}
else if (choice != 1 || choice != 2 || choice != 3 || choice != 4 ){
system("cls");
printf("please choose level:\n");
printf("1 - easy (20 rounds)\n");
printf("2 - normal (15 rounds)\n");
printf("3 - hard (10 rounds)\n");
printf("4 - crazy (random number of rounds 5-25)\n");
printf("Make a choice:");
_flushall();
scanf("%1d",&choice);
}
} while (returnV != 'n');
}
system("PAUSE");
}
header file to connect:
char levels (int level);
"levels" function:
#include <stdio.h>
#include "connect.h"
#include <time.h>
#include <stdlib.h>
char cases (int myCase, char crazyl);
char levels (int level) {
char crazyl = 'n',playerChoice;
switch (level){
case (20):
playerChoice = cases (level,crazyl);
printf ("\n%c\n",playerChoice);
return playerChoice;
break;
case (15):
playerChoice = cases (level,crazyl);
return playerChoice;
break;
case (10):
playerChoice = cases (level,crazyl);
return playerChoice;
break;
case (30):
crazyl = 'x';
level = rand() % (25 - 5 + 1);
playerChoice = cases (level,crazyl);
return playerChoice;
}
}
int ranGen (int code1,int code2, int code3, int code4);
char cases (int level,char crazyl)
{
unsigned int check;
char choise = 't',code1,code2,code3,code4;
if(level > 0){
while (level > 0){
if(crazyl == 'n'){
printf("Write your guess (only 1-6, no ENTER is needed) [%d guess left]\n",level);
}
else if (crazyl == 'x'){
printf("Write your guess (only 1-6, no ENTER is needed) [xxx guess left]\n");
}
code1 = getch();
printf("%c",code1);
code2 = getch();
printf("\t%c",code2);
code3 = getch();
printf("\t%c\t",code3);
code4 = getch();
printf("%c\n",code4);
if(code1 > '0' && code1 < '7' && code2 > '0' && code2 < '7' && code3 > '0' && code3 < '7' && code4 > '0' && code4 < '7'){
check = ranGen(code1,code2,code3,code4);
level--;
} else {
printf("\nnot a good number only numbers between 1-6\n");
level--;
}
if (level == 0) {
printf("FOR GOD SAKE WE LOST!!!\n");
printf("The secret password was:\n");
while (choise != 'y' || choise != 'n') {
if (choise != 'y' || choise != 'n') {
printf("keep playing? (y/n):");
_flushall();
scanf("%1c",&choise);
if (choise == 'y' || choise == 'n' ) {
return choise;
} else {
continue;
}
}
}
}
}
}
}
int ranGen(int code1,int code2, int code3, int code4) {
unsigned int ranCode[3],check,code[3];
code[0] = (int) code1 - 48;
code[1] = (int) code2 - 48;
code[2] = (int) code3 - 48;
code[3] = (int) code4 - 48;
do {
ranCode[0] = rand() % (6 - 1 + 1);
ranCode[1] = rand() % (6 - 1 + 1);
ranCode[2] = rand() % (6 - 1 + 1);
ranCode[3] = rand() % (6 - 1 + 1);
} while (code[0] != ranCode[0] || code[1] != ranCode[1] || code[2] != ranCode[2] || code[3] != ranCode[3]);
}
Now my problem is in ranGen function at "levels" paste.
I need to Generate 4 random numbers between 1-6 that different from each other
(1234 is ok, 1878 not ok, 2234 not ok either) and that the user will guess the digits while if he made a correct digits lets say:
generated code = 2345
guess = 1364
The user will get: 1 HIT and 1 MISS while if user will input 2222 he will get 1 HIT and 3 MISSES.
Now im pretty lost here and any help will be great.
I see the problems in your ranGen() function...
you have...
unsigned int ranCode[3],check,code[3];
ranCode[3] gives you 3 elements in that array. Array elements start counting at zero, so that would give you ranCode[0], ranCode[1] and ranCode[2]. If you want ranCode[3] and code[3], than you need to change the above line to...
unsigned int ranCode[4],check,code[4];
That gives you 4 elements, numbered from 0 to 3 (0, 1, 2 & 3 equals 4 numbers).
I'm also not certain what you are trying to do with...
ranCode[0] = rand() % (6 - 1 + 1);
...in your program, it will evaluate what is inside the brackets first, so 6 - 1 = 5, + 1 = 6. So in essence, that line will also look like ranCode[0] = rand() % 6; to the compiler and will give a number from 0 to 5. If you wish to add one to the result, you can use: ranCode[0] = (rand() % 6) + 1;, that would do the random number first, then add one to it for 1 to 6 (which is what I assume you wanted for a dice roll?).
Anyhow, you're passing code4 to a nonexistent element, out of range and probably corrupting memory somewhere, which would have undefined behaviour, possibly crash the system, or effect another variable's memory etc.

C: How do I break this loop in my code?

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{}.

Coding Tic Tac Toe in C with only If statements

So the past week I've been attempting to learn some C, I was giving an exercise to code a really simplistic version of tic tac toe.
I have been asked:
Prompt two users to enter a ‘naught’ or a ‘cross’ respectively into one of the nine positions on the tic, tac, toe grid
After all 9 inputs have been made display the grid
To make it simpler: only when all 9 grid positions have been entered figure out if there is a winner (you can do this with a few ‘if’ statements)
.
I'm told this can be done with a few if statements, so far I have only learnt up to if's, including the basic int, char, float, double, ect.
So, what I'm not truly grasping in how to only use if statements to check if:
the position is already taken, if it has prompt the user to try again or place the current persons naught or cross in that position.
keep track of the positions the two users enter, so I know which position each of the two users they have entered to check those positions if its empty or not.
I feel like I am somewhat over thinking this but I am unsure, if anyone has got any help that'd be great.
This is what I've written so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char board[9];
int num;
printf("Today we are playing a game of Tic Tac Toe\n");
printf("To play the game you need to line up 3 of the same type 'x's or o's' in a line to win\n");
printf("Before we start, whoever wants to be 'X' starts first, and whoever wants to be 'O' starts second\n");
printf("The board looks like this\n");
printf("%d%c%d%c%d\n", 1, 124, 2, 124, 3);
printf("%d%c%d%c%d\n", 4, 124, 5, 124, 6);
printf("%d%c%d%c%d\n", 7, 124, 8, 124, 9);
printf("Lets begin");
printf("\n");
printf("\n");
printf("\n");
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'O';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'O';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'O';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'O';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
return 0;
}
Note: Could I also ask that all answers be kept to only using if statements as that is as far as I am up too, and it is how the exercise is meant to be completed, although probably this is ten times easier with for/while and arrays.
Thank you!
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define ROWS 3
#define COLUMNS 3
#define PLAYER_ONE 'X'
#define PLAYER_TWO 'O'
void board();//calling class required by C
int checkForWinner();//calling class required by C
char tic_tac_toe[ROWS][COLUMNS] =
{
{ '1', '2', '3'},
{ '4', '5', '6'},
{ '7', '8', '9'}
};
int main()
{
int isGameOn=1, currentPlayer=1, pick;
char checked;
do
{
board();
currentPlayer = (currentPlayer % 2) ? 1 : 2;
printf("Player %d, pick a number: ", currentPlayer);
scanf("%d", &pick);
checked = (currentPlayer == 1) ? 'X' : 'O';
isGameOn = checkForWinner();
if(pick == 1 && tic_tac_toe[0][0] == '1'){
tic_tac_toe[0][0] = checked;
if(isGameOn == 1)break;
}else if(pick == 2 && tic_tac_toe[0][1] == '2'){
tic_tac_toe[0][1] = checked;
if(isGameOn == 1){break;}
}else if(pick == 3 && tic_tac_toe[0][2] == '3'){
tic_tac_toe[0][2] = checked;
if(isGameOn == 1){break;}
}else if(pick == 4 && tic_tac_toe[1][0] == '4'){
tic_tac_toe[1][0] = checked;
if(isGameOn == 1){break;}
}else if(pick == 5 && tic_tac_toe[1][1] == '5'){
tic_tac_toe[1][1] = checked;
if(isGameOn == 1){break;}
}else if(pick == 6 && tic_tac_toe[1][2] == '6'){
tic_tac_toe[1][2] = checked;
if(isGameOn == 1){break;}
}else if(pick == 7 && tic_tac_toe[2][0] == '7'){
tic_tac_toe[2][0] = checked;
if(isGameOn == 1){break;}
}else if(pick == 8 && tic_tac_toe[2][1] == '8'){
tic_tac_toe[2][1] = checked;
if(isGameOn == 1){break;}
}else if(pick == 9 && tic_tac_toe[2][2] == '9'){
tic_tac_toe[2][2] = checked;
if(isGameOn == 1){break;}
}
else{
printf("Invalid moved");
}
isGameOn = checkForWinner();
if(isGameOn == 1){
printf("***************************************\n");
printf("The winner is player %d\n", currentPlayer);
printf("***************************************");
break;
}
currentPlayer++;
}while(isGameOn == -1);
board();
return(0);
}
/*Functions*/
/*Board display*/
void board()
{
printf("\n");
printf("%c\t %c\t %c\n", tic_tac_toe[0][0], tic_tac_toe[0][1], tic_tac_toe[0][2]);
printf("%c\t %c\t %c\n", tic_tac_toe[1][0], tic_tac_toe[1][1], tic_tac_toe[1][2]);
printf("%c\t %c\t %c\n", tic_tac_toe[2][0], tic_tac_toe[2][1], tic_tac_toe[2][2]);
}
/*Checking for winner*/
int checkForWinner()
{
/*checkign vertical line*/
for(int col=0; col<COLUMNS; col++){
int row=0;
if(tic_tac_toe[row][col] == tic_tac_toe[row+1][col] && tic_tac_toe[row+1][col] == tic_tac_toe[row+2][col]){
return 1;
}
}
/*checking horizontal line*/
if(tic_tac_toe[0][0] == tic_tac_toe[0][1] && tic_tac_toe[0][1] == tic_tac_toe[0][2]){
return 1;
}
else if(tic_tac_toe[1][0] == tic_tac_toe [1][1] && tic_tac_toe[1][1] == tic_tac_toe[1][2])
{
return 1;
}
else if(tic_tac_toe[2][0] == tic_tac_toe [2][1] && tic_tac_toe[2][1] == tic_tac_toe[2][2])
{
return 1;
}
else if(tic_tac_toe[0][0] == tic_tac_toe[1][1] && tic_tac_toe[1][1] == tic_tac_toe[2][2])/*diagonal*/
{
return 1;
}
else {
return -1;
}
}

Resources