I am in an introduction-to-C-programming class and we were assigned to write a Hangman program.
In the game, the computer chooses a word at random and shows how many letters it has. The user must guess the word by entering a letter they think might be in the word. Also the user only has six chances to get the word correct. With every wrong guess the picture of the being hanged will be completed. The program needs to have a main menu with three options (New game, Score and Quit). The program also needs to have these three functions:
selectWord to make a random selection of words (I created a string of words within this function).
drawMan to draw the hangman.
checkWord to check to see if the input is correct and replaces dashes with correct letters.
The problem for me occurs when I run the game and instead of shows the dashes the line where the dashed are supposed to be just says (null). The picture still displays though.
I am perplexed as to what might be causing this. Here is what I have so far:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char selectWord(char []);
int drawMan(int);
void checkWord(char, char [], char [], int, int);
int main()
{
int menuSelect;
int chances = 0;
char word[13];
int length;
int score;
do
{
printf("\n\t\t\tThe Hangman Game v1.0 has booted\n\n");
printf("\t\t[1]\t Create new game\n");
printf("\t\t[2]\t View Score\n");
printf("\t\t[3]\t Exit game\n");
printf("Please enter a number from the menu: ");
scanf("%d", &menuSelect);
switch(menuSelect)
{
case 1:
selectWord(word);
length = strlen(word);
char dash[20]; //Will create dashes considering the length of the selected word
int dashCount;
int letterTry;
int wordMatch = 0;
for(dashCount = 0; dashCount < length; dashCount++)
{
dash[dashCount] = '-';
}
dash[dashCount] = '\0';
while(wordMatch != 1)
{
drawMan(chances);
printf("\n%s", dash[dashCount]);
printf("\n\nPlease enter a letter: ");
fflush(NULL);
while(letterTry != '\n')
{
letterTry = getchar();
}
letterTry = getchar();
if(strcmp(dash, word) == 0)
{
printf("\nThat is correct!\n");
wordMatch = 1;
score++;
}
}
break;
case 2:
printf("The score is: %d", score);
break;
case 3:
printf("Thank you for playing!");
break;
}
}while(menuSelect != 3);
}
char selectWord(char word[])
{
int index;
char list[65][13]={{"sailboat"}, {"school"}, {"rug"}, {"chalk"}, {"tusk"}, {"camera"}, {"pajamas"}, {"cello"}, {"cake"}, {"beehive"}, {"gate"}, {"swing"}, {"lighthouse"}, {"toe"}, {"newspaper"}, {"stingray"}, {"brain"}, {"french"}, {"purse"}, {"soda"}, {"money"}, {"dryer"}, {"scale"}, {"clam"}, {"knee"}, {"artist"}, {"stomach"}, {"ticket"}, {"face"}, {"TV"}, {"can"}, {"blowfish"}, {"popsicle"}, {"beaver"}, {"snowball"}, {"dollar"}, {"sprinkler"}, {"hair"}, {"bathroom"}, {"rain"}, {"skirt"}, {"beach"}, {"suitcase"}, {"garden"}, {"doormat"}, {"pretzel"}, {"watering"}, {"fur"}, {"birthday"}, {"fries"}, {"owl"}, {"chin"}, {"spool"}, {"mushroom"}, {"peach"}, {"pelican"}, {"pineapple"}, {"flagpole"}, {"doghouse"}, {"boot"}, {"flute"}, {"quilt"}, {"hook"}, {"rainbow"}, {"happy"}};
srand(time(NULL));
index = rand()%65;
strcpy(word, list[index]);
return word;
}
int drawMan(int chances)
{
if(chances == 6)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | ");
printf("\n | ");
printf("\n |");
printf("\n |");
printf("\n /|\\\n\n");
}
else if(chances == 5)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | O");
printf("\n | |");
printf("\n |");
printf("\n |");
printf("\n /|\\\n\n");
}
else if(chances == 4)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | O");
printf("\n | /|");
printf("\n | ");
printf("\n | ");
printf("\n /|\\\n\n");
}
else if(chances == 3)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | O");
printf("\n | /|\\");
printf("\n | ");
printf("\n | ");
printf("\n /|\\\n\n");
}
else if(chances == 2)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | O");
printf("\n | /|\\");
printf("\n | ");
printf("\n | ");
printf("\n /|\\\n\n");
}
else if(chances == 1)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | O");
printf("\n | /|\\");
printf("\n | /");
printf("\n | ");
printf("\n /|\\\n\n");
}
else if(chances == 0)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | O");
printf("\n | /|\\");
printf("\n | / \\");
printf("\n | ");
printf("\n /|\\\n\n");
printf("\n\n\t You have lost!");
}
}
void checkWord(char ltrTry, char word[], char dash[], int length, int chances)
{
int count;
int correct = 0; // 0 is incorrect 1 is correct
for(count = 0; count < length; count++)
{
if(ltrTry == word[count])
{
dash[count] = word[count];
correct = 1;
}
}
}
Update #1: Thank you all for the dash string fix. Adding null character to the dash array fixed the dash problem. I added a new variable to case 1 in my main function called "wordMatch" and made it my control variable for the while loop since it's possible to get the word correct and exit the loop withuot using up all the chances. But it seems a new one has arisen. When selecting new game, the hangman is displayed twice and upon entering an incorrect letter the number of chances does not change nor does the image of the hangman change (giving me unlimited trys). However the loop exits correctly once I guess the word correctly. Why might this be happening?
Update #2: I have corrected the code and gotten it to perform correctly. The only problem now seems that the case 1 doesn't break, because it is stuck in the while loop with letterTry.
There are actually 2 problems. After assigning dashes, make sure that you terminate the string with \0 as follows:
for(dashCount = 0; dashCount < length; dashCount++)
{
dash[dashCount] = '-';
}
dash[dashCount] = '\0';
And in the while loop, print:
printf("\n%s", dash);
instead of:
printf("\n%s", dash[dashCount]);
Also, you are not updating the chances value after each try. You can do this by making checkWord function to return the correct and updating the chances count based on that, as follows:
int checkWord(char ltrTry, char word[], char dash[], int length, int trys)
{
...
return correct;
}
And in the loop, instead of just calling the function, do the following:
if(!checkWord(letterTry, word, dash, length, chances))
{
chances++;
}
Another problem I can see is while reading the letterTry value. When you read a character (in this case letterTry) after using scanf function before, the \n character will get stored in the variable. Then the program will not prompt for another input from you. In your case, the player will loose one chance for no reason. The simplest solution for this problem is to do as follows:
while(letterTry != '\n')
letterTry = getchar();
And, break from the main loop once the player gets the answer right.
if(strcmp(dash, word) == 0)
{
printf("You Won!");
score++;
break;
}
After understanding the above solutions, correctly, go through this fixed solution:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char selectWord(char[]);
int drawMan(int);
int checkWord(char, char[], char[], int);
int main()
{
int menuSelect;
int chances = 0;
char word[13];
int length;
int score;
do
{
printf("\n\t\t\tThe Hangman Game v1.0 has booted\n\n");
printf("\t\t[1]\t Create new game\n");
printf("\t\t[2]\t View Score\n");
printf("\t\t[3]\t Exit game\n");
printf("Please enter a number from the menu: ");
scanf("%d", &menuSelect);
switch(menuSelect)
{
case 1:
selectWord(word);
length = strlen(word);
char dash[20]; //Will create dashes considering the length of the selected word
int dashCount;
int letterTry;
for(dashCount = 0; dashCount < length; dashCount++)
{
dash[dashCount] = '-';
}
dash[dashCount] = '\0';
chances = 0;
while(chances != 6)
{
drawMan(chances);
printf("\n%s\n", dash);
printf("chances = %d\n", chances);
printf("\n\nPlease enter a letter: ");
fflush(NULL);
//scanf("%c%c", &letterTry, &letterTry);
while(letterTry != '\n')
letterTry = getchar();
letterTry = getchar();
if(!checkWord(letterTry, word, dash, length))
{
chances++;
}
if(strcmp(dash, word) == 0)
{
printf("You Won!");
score++;
break;
}
}
break;
case 2:
printf("The score is: %d", score);
break;
case 3:
printf("Thank you for playing!");
break;
}
}while(menuSelect != 3);
}
char selectWord(char word[])
{
int index;
char list[65][13]={{"sailboat"}, {"school"}, {"rug"}, {"chalk"}, {"tusk"}, {"camera"}, {"pajamas"}, {"cello"}, {"cake"}, {"beehive"}, {"gate"}, {"swing"}, {"lighthouse"}, {"toe"}, {"newspaper"}, {"stingray"}, {"brain"}, {"french"}, {"purse"}, {"soda"}, {"money"}, {"dryer"}, {"scale"}, {"clam"}, {"knee"}, {"artist"}, {"stomach"}, {"ticket"}, {"face"}, {"TV"}, {"can"}, {"blowfish"}, {"popsicle"}, {"beaver"}, {"snowball"}, {"dollar"}, {"sprinkler"}, {"hair"}, {"bathroom"}, {"rain"}, {"skirt"}, {"beach"}, {"suitcase"}, {"garden"}, {"doormat"}, {"pretzel"}, {"watering"}, {"fur"}, {"birthday"}, {"fries"}, {"owl"}, {"chin"}, {"spool"}, {"mushroom"}, {"peach"}, {"pelican"}, {"pineapple"}, {"flagpole"}, {"doghouse"}, {"boot"}, {"flute"}, {"quilt"}, {"hook"}, {"rainbow"}, {"happy"}};
srand(time(NULL));
index = rand()%65;
strcpy(word, list[index]);
return word;
}
int drawMan(int chances)
{
if(chances == 0)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | ");
printf("\n | ");
printf("\n |");
printf("\n |");
printf("\n /|\\\n\n");
}
else if(chances == 1)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | O");
printf("\n | |");
printf("\n |");
printf("\n |");
printf("\n /|\\\n\n");
}
else if(chances == 2)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | O");
printf("\n | /|");
printf("\n | ");
printf("\n | ");
printf("\n /|\\\n\n");
}
else if(chances == 3)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | O");
printf("\n | /|\\");
printf("\n | ");
printf("\n | ");
printf("\n /|\\\n\n");
}
else if(chances == 4)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | O");
printf("\n | /|\\");
printf("\n | ");
printf("\n | ");
printf("\n /|\\\n\n");
}
else if(chances == 5)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | O");
printf("\n | /|\\");
printf("\n | /");
printf("\n | ");
printf("\n /|\\\n\n");
}
else if(chances == 6)
{
printf("\n\n");
printf("\n +-------+");
printf("\n | |");
printf("\n | O");
printf("\n | /|\\");
printf("\n | / \\");
printf("\n | ");
printf("\n /|\\\n\n");
printf("\n\n\t You have lost!");
}
printf("print complete; exiting successfully");
}
int checkWord(char ltrTry, char word[], char dash[], int length)
{
int count;
int correct = 0; // 0 is incorrect 1 is correct
for(count = 0; count < length; count++)
{
if(ltrTry == word[count])
{
dash[count] = word[count];
correct = 1;
}
}
/* if(correct == 0)
{
trys--;
} */
return correct;
}
Related
#include<stdio.h>
#include <stdlib.h>
int check();
void board();
int s[10]= {'0','1','2','3','4','5','6','7','8','9'};
int main()
{
char m;
int c, player=1, i, j;
printf("\t Tic\tTac\tToe\n");
printf(" \t player 1[X] \t player 2[O]\n\n");
do {
srand(time(0));
board();
if(player%2==1) {
player=1;
}
else {
player=2;
}
printf("\nplayer %d: ",player);
scanf("%d", & c);
if(player==1) {
m='X';
}
else if(player==2) {
m='O';
}
if(c==1 && s[1]=='1')
s[1]=m;
if(c==2 && s[2]=='2')
s[2]=m;
if(c==3 && s[3]=='3')
s[3]=m;
if(c==4 && s[4]=='4')
s[4]=m;
if(c==5 && s[5]=='5')
s[5]=m;
if(c==6 && s[6]=='6')
s[6]=m;
if(c==7 && s[7]=='7')
s[7]=m;
if(c==8 && s[8]=='8')
s[8]=m;
if(c==9 && s[9]=='9')
s[9]=m;
if(c>9) {
printf("\nInvalid choose Try again\n");
player--;
}
getchar();
system("clear");
i=check();
dup();
player++;
a++;
} while(i==-1);
board();
if (i==1)
printf("\n==>\aPlayer %d won\n\n ", --player);
if(i==0)
printf("\n==>\aGame is draw\n");
if(j==1) {
printf("\nInvalid choose Try again\n");
player--;
}
return 0;
}
void board()
{
printf("\n | | \n");
printf(" %c | %c | %c\n", s[1],s[2],s[3]);
printf("_________|____|_________\n");
printf(" | | \n");
printf(" %c | %c | %c\n", s[4],s[5],s[6]);
printf("_________|____|_________\n");
printf(" | | \n");
printf(" %c | %c | %c\n", s[7],s[8],s[9]);
}
int check() {
if(s[1]==s[2] && s[2]==s[3])
return 1;
if(s[4]==s[5] && s[5]==s[6])
return 1;
if(s[7]==s[8] && s[8]==s[9])
return 1;
if(s[1]==s[4] && s[4]==s[7])
return 1;
if(s[2]==s[5] && s[5]==s[8])
return 1;
if(s[3]==s[6] && s[6]==s[9])
return 1;
if(s[1]==s[5] && s[5]==s[9])
return 1;
if(s[3]==s[5] && s[5]==s[7])
return 1;
if(s[1]!='1'&& s[2]!='2' && s[3]!='3' && s[4]!='4'&& s[5]!='5'&& s[6]!='6'&& s[7]!='7'&& s[8]!='8'&& s[9]!='9')
return 0;
else
return -1;
}
**I am a begginer so if the way I am questioning is wrong plz feel free to ask me I will try my best to tell you my issue.i tried a lot to execute a warning when player tries to enter the number that already has 'X' or 'Y' but I was unsuccessful with no clue to do it on correct way.**I was successful to make it possible for s[1] but I couldn't apply that for all as it would be long process to gradually make the condition for each and every blocks so i am here if anyone could tell me a less lengthy and in more useful way. Thanks, hoping to get some suggestions.
I'm trying to create a program that allows users to add information into a nameCard array using a function called AddNameCard. but when I try to add another set of input in, the previous items seems to get overwritten. and the listnamecard function only displays the last inputted items. Anyone know what i need to do to get around this problem? I'm learning C programming currently, go easy on me please :).
#include <stdio.h>
#include <stdlib.h>
# define Max_Size 5
typedef struct
{
int nameCardID;
char personName[20];
char companyName[20];
} NameCard;
NameCard nameCard[Max_Size];
void AddNameCard() {
int j;
printf("\n");
for (int i = j - 1; i < j; i++){
printf("Enter Name Card ID: \n");
scanf("%d", &nameCard[i].nameCardID);
printf("Enter Person Name: \n");
scanf("%s", &nameCard[i].personName);
printf("Enter Company Name : \n");
scanf("%s", &nameCard[i].companyName);
}
printf("\n");
return;
}
void ListNameCard() {
int j;
printf("\n");
printf("\nName_Card_ID Person_Name Company_Name \n");
for (int i = 0; i < j; i++){
printf("%d %s %s \n", nameCard[i].nameCardID, nameCard[i].personName, nameCard[i].companyName);
}
printf("\n");
return;
}
void GetNameCard() {
printf("%d %s %s", nameCard[1].nameCardID, nameCard[1].personName, nameCard[1].companyName);
}
int main()
{
int options;
while (options != 5) {
printf("1:List Name Cards\n2:Add Name Card\n3:Remove Name Cards\n4:Get Name Cards\n5:quit\n");
printf("\n");
printf("What would you like to do? : ");
scanf("%d", &options);
switch (options)
{
case 1:
ListNameCard();
break;
case 2:
AddNameCard();
break;
case 3:
printf("Case3 ");
printf("\n");
break;
case 4:
GetNameCard();
break;
default:
printf("quit ");
}
}
#include <stdio.h>
#include <stdlib.h>
#define Max_Size 5
typedef struct {
int nameCardID;
char personName[20];
char companyName[20];
}
NameCard;
NameCard nameCard[Max_Size];
void AddNameCard() {
printf("\n");
int i;
printf("enter the number of person you want to add :");
scanf("%d", & i);
printf("Enter Name Card ID: \n");
scanf("%d", & nameCard[i - 1].nameCardID);
printf("Enter Person Name: \n");
scanf("%s", nameCard[i - 1].personName);
printf("Enter Company Name : \n");
scanf("%s", nameCard[i - 1].companyName);
printf("\n");
return;
}
void ListNameCard() {
printf("\n");
printf("\nName_Card_ID Person_Name Company_Name \n");
for (int i = 0; i < Max_Size; i++) {
printf("%d %s %s \n", nameCard[i].nameCardID, nameCard[i].personName, nameCard[i].companyName);
}
printf("\n");
return;
}
void GetNameCard() {
int n;
printf("\n");
printf("enter the number of the person");
scanf("%d", & n);
printf("%d %s %s", nameCard[n - 1].nameCardID, nameCard[n - 1].personName, nameCard[n - 1].companyName);
printf("\n");
}
int main() {
int options;
while (options != 5) {
printf("1:List Name Cards\n2:Add Name Card\n3:Remove Name Cards\n4:Get Name Cards\n5:quit\n");
printf("\n");
printf("What would you like to do? : ");
scanf("%d", & options);
switch (options) {
case 1:
ListNameCard();
break;
case 2:
AddNameCard();
break;
case 3:
printf("Case3 ");
printf("\n");
break;
case 4:
GetNameCard();
break;
default:
printf("quit ");
}
}
}
Let's follow the comments' suggestions.
First we avoid using options variable uninitialized by changing:
while (options != 5) {
...
}
To:
do {
... (set options variable here)
} while (options != 5);
Secondly, we change the name of j variable to count and use it as function parameter/return so we keep track and update the number of added cards. For instance, AddNameCard becomes:
int AddNameCard(int count)
{
if (count < Max_Size) {
count++;
int i = count - 1;
printf("\n");
printf("Enter Name Card ID: ");
scanf("%d", &nameCard[i].nameCardID);
discard_newline();
printf("Enter Person Name: ");
scanf("%19[^\n]", nameCard[i].personName);
discard_newline();
printf("Enter Company Name: ");
scanf("%19[^\n]", nameCard[i].companyName);
discard_newline();
} else {
printf("Maximum number of cards reached\n");
}
printf("\n");
return count;
}
(discard_newline prevents newline characters to creep into the next scanf. "%19[^\n]" format prevents buffer overrun into 20 length strings.)
The name of an array variable is already taken as its address (or the address of its first element). So personName and companyName members shouldn't be preceded by &.
The code becomes:
#include <stdio.h>
#include <stdlib.h>
#define Max_Size 5
typedef struct
{
int nameCardID;
char personName[20];
char companyName[20];
} NameCard;
NameCard nameCard[Max_Size];
void discard_newline(void)
{
while( getchar() != '\n' );
}
int AddNameCard(int count)
{
if (count < Max_Size) {
count++;
int i = count - 1;
printf("\n");
printf("Enter Name Card ID: ");
scanf("%d", &nameCard[i].nameCardID);
discard_newline();
printf("Enter Person Name: ");
scanf("%19[^\n]", nameCard[i].personName);
discard_newline();
printf("Enter Company Name: ");
scanf("%19[^\n]", nameCard[i].companyName);
discard_newline();
} else {
printf("Maximum number of cards reached\n");
}
printf("\n");
return count;
}
void ListNameCard(int count) {
if (count > 0) {
printf("\nName_Card_ID Person_Name Company_Name\n");
for (int i = 0; i < count; i++){
printf("%d %s %s \n", nameCard[i].nameCardID, nameCard[i].personName, nameCard[i].companyName);
}
} else {
printf("Empty list: none added yet\n");
}
printf("\n");
return;
}
void GetNameCard() {
printf("%d %s %s", nameCard[1].nameCardID, nameCard[1].personName, nameCard[1].companyName);
}
int main()
{
int options;
int count = 0;
do {
printf("1:List Name Cards\n2:Add Name Card\n3:Remove Name Cards\n4:Get Name Cards\n5:quit\n");
printf("\n");
printf("What would you like to do? : ");
scanf("%d", &options);
switch (options)
{
case 1:
ListNameCard(count);
break;
case 2:
count = AddNameCard(count);
break;
case 3:
printf("Case3 ");
printf("\n");
break;
case 4:
GetNameCard();
break;
default:
printf("quit\n");
}
} while (options != 5);
}
Running it:
1:List Name Cards
2:Add Name Card
3:Remove Name Cards
4:Get Name Cards
5:quit
What would you like to do? : 1
Empty list: none added yet
1:List Name Cards
2:Add Name Card
3:Remove Name Cards
4:Get Name Cards
5:quit
What would you like to do? : 2
Enter Name Card ID: 123
Enter Person Name: John Smith
Enter Company Name: COMP_01
1:List Name Cards
2:Add Name Card
3:Remove Name Cards
4:Get Name Cards
5:quit
What would you like to do? : 1
Name_Card_ID Person_Name Company_Name
123 John Smith COMP_01
1:List Name Cards
2:Add Name Card
3:Remove Name Cards
4:Get Name Cards
5:quit
What would you like to do? : 5
quit
You still have to complete the other options.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am making a tic tac toe game in C language but it won't run
I don't know where is the error at. The compiler just freeze without any error messages this is my code below if anyone could point out the errors and the way of writing clean code i am a new programmer who is still learning and this is my first project.
#include <stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h>
void BuildGround;
void first_player_choice;
void second_player_choice;
void ai_choice;
char result;
void AiVsP;
void PVP;
int count_ground;
int main()
{
char ground[9] = {' ',' ',' ',' ',' ',' ',' ',' ',' '};
int mode;
printf("choose game mode (1 or 2): ");
printf("1. PVP ");
printf("2. AI vs P: ");
scanf("%d",&mode);
switch(mode){
case 1 :
PVP();
break;
case 2:
AiVsP();
break;
default:
printf("Invalid input: ");
break;
}
}
int count_ground(char symbole){
int total=0;
for(int i =0 ; i<9 ; i++){
if(ground[i]== symbole)
total=+ 1;
}
}
void AiVsP(void){
char name[100];
printf("Enter your name : ");
gets(name);
while(1==1){
system("cls");
BuildGround();
if (count_ground('X') == count_ground('O')){
puts("Turn: ");
puts(name);
fisrt_player_choice();
}
else{
ai_choice;
}
char winner == result();
if (winner == 'X'){
system("cls");
BuildGround();
puts("The winner is: ");
puts(name);
break;
}
else if
(winner == 'O'){
system("cls");
BuildGround();
printf("AI wins ")
break;
}
else winner == 'D'
printf("The Game is Draw ")
break;
}
}
void PVP(void){
char name1[100];
char name2[100];
printf("Enter the name of the first player : ");
gets(name1);
printf("Enter the name of the second player : ");
gets(name2);
while(1==1){
system("cls");
BuildGround;
if (count_ground('X') == count_ground('O')){
puts("Turn: ");
puts(name1);
first_player_choice();
}
else{
puts("Turn: ");
puts(name2);
second_player_choice();
}
char winner == result();
if (winner == 'X'){
system("cls");
BuildGround();
puts("The winner is: ");
puts(name1);
break;
}
else if
(winner == 'O'){
system("cls");
BuildGround();
puts("The winner is: ");
puts(name2);
break;
}
else winner == 'D'
printf("The Game is Draw ")
break;
}
}
char result(char ground[9]){
int i;
for(i = 0;i<=6; i+=3)//it's for row
if(ground[i] == ground[i+1]== && ground[i+1]== ground[i+2]&& ground[i] != ' ' ){
return ground[0];
}
for(i = 0;i<3; i++)//it's for column
if(ground[i]== ground[i+3]== && ground[i+3]== ground[i+6] && ground[i]!=' ' ){
return ground[1];
}
if(ground[0] == && ground[4] == && ground[4]== ground[8] && ground[0]!=' '){
return ground[4];
}
else if(ground[2] == && ground[4] == && ground[4]== ground[6] && ground[2]!=' '){
return ground[6];
}
else if(count_ground('X')+ count_ground('O') < 9){
return 'C';
}else return 'D';
}
void ai_choice(void){
srand(time(0));
do{
int c;
c = rand()%10;
}
while(ground[c]!= ' ');
ground(c)='O';
}
void first_player_choice(char ground[9]){
while(1==1){
int position;
printf("Choose your position from 0-8 (column wise): ");
scanf("%d", &position);
if(position < 0 || position > 8 ){
printf("Invalid number please try again: ");
}
else if(ground[position]!=' '){
printf("Position is already taken please try again: ");
}
else
ground[c]='X';
break;
}
}
void second_player_choice(char ground[9]){
while(1==1){
int position;
printf("Choose your position from 0-8 (column wise): ");
scanf("%d", &position);
if(position < 0 || position > 8 ){
printf("Invalid number please try again: ");
}
else if(ground[position]!=' '){
printf("Position is already taken please try again: ");
}
else
ground[c]='O';
break;
}
}
void BuildGround(char ground[9]){
printf("\t\t\t\tT i c t a c t o e");
printf("\nPlayers 1 Symbol: X");
printf("\nPlayers 2 Symbol: O");
printf("\n\t\t\t | | ");
printf("\n\t\t\t %c | %c | %c ",ground[0],ground[1],ground[2]);
printf("\n\t\t\t_______|_______|_______");
printf("\n\t\t\t %c | %c | %c ",ground[3],ground[4],ground[5]);
printf("\n\t\t\t_______|_______|_______");
printf("\n\t\t\t %c | %c | %c ",ground[6],ground[7],ground[8]);
printf("\n\t\t\t | | ");
}
You have multiple issues, like
case 1 :
PVP; //this is not a function call.
break;
should use the call like
PVP();
or rather, pvp(); , as uppercase letters usually carry special meaning, not a good idea to use them for user-defined code.
That said, function definitions like
void ai_choice{
srand(time(0));
and
void PVP{
char name1[100];
char name2[100];
are wrong syntax, you have to use the parenthesis, like
void PVP (void){
char name1[100];
char name2[100];
That said, scanf("%d",& mode); is usually written as scanf("%d",&mode); (no space between operand and operator, but that's just a choice).
I am making simple C program. This program should be able to store data in memory (not using database). But when i tested it, it can not store more than 1 data. Every time i store new data, the old one get replaced. I hope these screenshot could help you understand what i mean.
As you can see, i input first set of data. It shows up with no problem.
Then, i added second set of data. Where is the first data ? The No 2 Data supposed to be after the No 1 data. But the first data get lost at all.
This is my input code :
//this is function for the input
void masukan() {
n=n+1; //use n as index for the struct (mhsw)
printf("\n");
printf("Masukkan NIM : "); scanf("%s", mhsw[n].nim);
printf("Masukkan Nama : "); scanf("%s", mhsw[n].nama);
printf("Masukkan Golongan UKT : "); scanf("%d", &mhsw[n].golUKT);
mhsw[n].nominalUKT = nominal(mhsw[n].golUKT)*100000;
printf("");
}
//the nominal UKT = factorial of golUKT
int nominal(int n) {
int hasil = 0;
if (n == 1) return 15;
else {
hasil = ((n*n) + nominal(n-1));
return hasil;
}
}
This is my output code :
//this is for the output
void tampil() {
if (!kbhit()) {
printf("\n");
printf(" ===========================================================================\n");
printf(" DATA MAHASISWA \n");
printf("|====|================|====================|==============|=================|\n");
printf("| No | NIM | Nama | Golongan UKT | Nominal UKT |\n");
printf("|====|================|====================|==============|=================|\n");
for(i=0; i<n; i++); //to display record
{
printf("%5d", i);
printf("%17s", mhsw[i].nim);
printf("%20s", mhsw[i].nama);
printf("%15d", mhsw[i].golUKT);
printf("%18d", mhsw[i].nominalUKT);
printf("\n");
}
printf("|====|================|====================|==============|=================|\n");
printf("\n \nPencet sembarang tombol untuk kembali ke Home");
getch();
} else {
menu();
}
}
This is the whole code :
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <windows.h>
//global variable
struct mahasiswa
{
char nim[10];
char nama[50];
int golUKT;
long int nominalUKT;
};
struct mahasiswa mhsw[50];
int i, n, nim;
bool ada = false;
char carinim[10];
//prototype
void login();
void menu();
void gotoxY(int, int);
void loading();
void masukan();
int nominal(int);
void tampil();
void cari();
//main function
void main() {
login();
}
void login() {
char user[10], pass[10];
int x, y;
printf("Masukkan Username : "); scanf("%s", user);
printf("Masukkan Password : "); scanf("%s", pass);
x = strcmp(user, "admin");
y = strcmp(pass, "admin123");
if (x == 0 && y == 0) {
menu();
}
else {
system("cls");
printf("Gagal Login, Ulangi Proses\n");
login();
}
}
void menu()
{
int pilih;
system("cls");
printf(" ____________________________________________________\n");
printf("| Siukat Lite |\n");
printf("|____________________________________________________|\n");
printf("|_______________________Home_________________________|\n");
printf("| 1. Pendaftaran Mahasiswa |\n");
printf("| 2. Daftar Golongan UKT |\n");
printf("| 3. Cari NIM |\n");
printf("| 4. Cetak Data Siukat |\n");
printf("| Ketik sembarang nomor untuk keluar |\n");
printf("|____________________________________________________|\n");
printf("Masukkan Pilihan Nomor : ");
scanf("%d",&pilih);
switch(pilih)
{
case 1:
//loading();
printf("\nPendaftaran Mahasiswa");
masukan();
menu();
break;
case 2:
case 3:
printf("Cari NIM");
cari();
break;
case 4:
//loading();
printf("\nData Siukat");
tampil();
default:
menu();
}
}
void gotoxy (int x,int y)
{
HANDLE hConsoleOutput;
COORD dwCursorPosition;
dwCursorPosition.X = x;
dwCursorPosition.Y = y;
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hConsoleOutput,dwCursorPosition);
}
void loading() {
int a;
char x;
gotoxy(1,12);
for(a=0;a<=5;a++)
{
usleep(500000);
printf("*",x);
}
}
//for input record
void masukan() {
printf("\n");
printf("Masukkan NIM : "); scanf("%9s", mhsw[n].nim);
printf("Masukkan Nama : "); scanf("%49s", mhsw[n].nama);
printf("Masukkan Golongan UKT : "); scanf("%d", &mhsw[n].golUKT);
mhsw[n].nominalUKT = nominal(mhsw[n].golUKT)*100000;
printf("");
n=n+1;
}
int nominal(int n) {
int hasil = 0;
if (n == 1) return 15;
else {
hasil = ((n*n) + nominal(n-1));
return hasil;
}
}
//for find NIM
void cari() {
printf("\nMasukkan NIM :"); scanf("%s", carinim);
printf("\n");
if (!kbhit()) {
for(i=0; i<n; i++) {
if (strcmp(carinim, mhsw[i].nim) == 1) {
ada = true;
} else {
ada = false;
}
}
if(ada) {
printf("NIM : %s \n", mhsw[i].nim);
} else {
printf("Data Tidak Ditemukan");
}
} else {
menu();
}
}
//for showing the record
void tampil() {
if (!kbhit()) {
printf("\n");
printf(" ===========================================================================\n");
printf(" DATA MAHASISWA \n");
printf("|====|================|====================|==============|=================|\n");
printf("| No | NIM | Nama | Golongan UKT | Nominal UKT |\n");
printf("|====|================|====================|==============|=================|\n");
for(i=0; i<n; i++);
{
printf("%5d", i);
printf("%17s", mhsw[i].nim);
printf("%20s", mhsw[i].nama);
printf("%15d", mhsw[i].golUKT);
printf("%18d", mhsw[i].nominalUKT);
printf("\n");
}
printf("|====|================|====================|==============|=================|\n");
printf("\n \nPencet sembarang tombol untuk kembali ke Home");
getch();
} else {
menu();
}
}
Thanks for any help
UPDATE : i tried to put increment after the insertion and see the value of n. Still doesn't work. Here is some screenshot.
The value of n before insertion is still 0
The value of n after insertion, it incremented to 1. But the data doesn't get recorded at all.
You have a ; after your for inside tampil().
for(i=0; i<n; i++);
It's causing your loop body to be empty so nothing is printed inside tampil().
To protect against such mistakes use a good compiler gcc and enable all warnings (for gcc it's -Wall -Wextra). Ex. gcc outputs this helpful warning message:
1.c: In function ‘tampil’:
1.c:167:9: warning: this ‘for’ clause does not guard... [-Wmisleading-indentation]
167 | for(i=0; i<n; i++);
| ^~~
1.c:168:9: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the ‘for’
168 | {
| ^
It is due to the fact that you do the n = n+1 instruction before the insertion in masukan(). You must move this instruction at the end of the function.
When the program starts, the value of n is 0. When you insert a new set of values, you first increment n and store thus the values at index 1. The values at index 0 are the default values.
When you print the values, you print the values with index 0 to n-1. This doesn't include the value at index n that you just inserted.
By moving the increment of n at the end of the new value insertion, the first value set will be inserted at index position 0 and n is the number of values in the table. n is also the index of the after last values in the table. This is where you insert the next value after what you increment n.
EDIT: another error is a ; after the for(i=0; i<n; i++) in the tampil function. That is the reason one line is printed regardless of the value of n.
I am a new C coder as of a few months working on a hangman game program. I have my code underneath this, and at the very bottom I have an outcome of what I want my code to look like. I am having trouble with a few errors I am receiving and any help works. I put the errors under this paragraph and above my code. I understand that the \ for my hangman diagram is an escape key, but I need to use it and somehow get around this error. Thanks!
line 38:9: warning: unknown escape sequence '\o'
line 46:9: warning: unknown escape sequence '\o'
line 54:9: warning: unknown escape sequence '\o'
line 62:9: warning: unknown escape sequence '\o'
line 70:9: warning: unknown escape sequence '\o'
line 72:9: warning: unknown escape sequence '\o'
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 25
#define MAX_WRONG_GUESSES 6
void check(char word[]){
while(strlen(word)>MAX_SIZE){
printf("ERROR: Input argument is too long\n");
break;
}
}
void hangman(int error_left){
if(error_left == 6){
printf("___ ");
printf("\n| ");
printf("\n| ");
printf("\n| ");
printf("\n-----");}
if(error_left == 5){
printf("___ ");
printf("\n| o ");
printf("\n| ");
printf("\n| ");
printf("\n-----");}
if(error_left == 4){
printf("___ ");
printf("\n|\o ");
printf("\n| ");
printf("\n| ");
printf("\n-----");}
if(error_left == 3){
printf("___ ");
printf("\n|\o/ ");
printf("\n| ");
printf("\n| ");
printf("\n-----");}
if(error_left == 2){
printf("___ ");
printf("\n|\o/ ");
printf("\n| | ");
printf("\n| ");
printf("\n-----");}
if(error_left == 1){
printf("___ ");
printf("\n|\o/ ");
printf("\n| | ");
printf("\n|/ ");
printf("\n-----");}
if(error_left == 0){
printf("___ ");
printf("\n|\o/ ");
printf("\n| | ");
printf("\n|/ \ ");
printf("\n-----");}
}
int guess(char word[]){
char in;
int x = 0;
int guesses, error_left;
for(guesses=0; guesses<strlen(word); guesses++){
for(error_left=MAX_WRONG_GUESSES; error_left>=0; error_left--){
printf("Guess a letter(%d attempts left) > ", error_left);
scanf(" %c", &in);
if(in != word[x] ){
error_left=error_left-1;
hangman(error_left);
printf("There are no %c's\n", in);
}else { error_left = error_left;
hangman(error_left);
printf("There is \n"); }
}
}
return error_left;
}
void game_over(int error_left){
printf("Game Over\n");
printf(" total guesses made\n");
if(error_left>0){
printf("You won!"); }
else {printf("Out of guesses\nYou lost."); }
}
int main(int argc, char *argv[]) {
char word[MAX_SIZE];
strcpy(word, argv[1]);
void check(char word[]);
int guess(char word[]);
void game_over(int error_left);
return (0);
}
./bonus kittycat
Guess a letter (6 attempts left) > q
| o
|
|
There are no q's
Guess a letter (5 attempts left) > w
|\o
|
|
There are no w's
Guess a letter (4 attempts left) > e
|\o/
|
|
There are no e's
Guess a letter (3 attempts left) > r
|\o/
| |
|
There are no r's
Guess a letter (2 attempts left) > t
|\o/
| |
|
**tt***t
There are 3 t's
Guess a letter (2 attempts left) > y
|\o/
| |
|
ttyt
There is 1 y
Guess a letter (2 attempts left) > u
|\o/
| |
|/
ttyt
There are no u's
Guess a letter (1 attempts left) > o
|\o/
| |
|/ \
ttyt
There are no o's
Game Over
8 total guesses made.
Out of guesses.
You lost.
If you need to printf one \, then print 2 of them (escape the escape) printf("\\");