So i have a program to data the users input.
in this program i want to make some function
to ask the user for the product coming in
to display the history of data coming in by sorting by date.
to ask the user for the product coming out
to display the history of data coming out by sorting by date.
to search a specific product data by calling the code
to display all the data, the data is sorted by date and then the weight is data coming in minus data coming out
actually i have made a complete program of this, but the teacher updated the assignment. in the previous assignment i mostly use array instead of pointer and for sorting i use recursive bubble sort.
For now i need someone's help to make a sort by date using binary tree and search by product code using binary tree
Note : i must use binary tree because that's the assignment my teacher gave me
assignments are :
have a function with address argument
have a function with array argument
have function with argument as address to a structure
have a function with structure argument
add node to linked list/stack/queue/tree
read/delete node from linked list/stack/queue/tree.
Honestly i still understand linked list/stack/queue/tree. i thought to make a linked list i just change my array to a pointer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
typedef struct {
int kode;
int amount;
char variety[20];
int weight;
int date;
}data;
data *innData;
data *outtData;
int menu;
int i;
int pointIn = 0, pointOut=0;
int amount = 0;
char variety[5][20] = {"Fish", "Crab", "Squid", "Clam", "Lobster"};
void sortDate(data *list, int range);
void back_menu();
void input();
void inputHistory();
void output();
void outHistory();
//void sort
//void calculateWeight
//void search();
//void showAll();
int main(){
innData=(data *)malloc(100*sizeof(data));
outtData=(data *)malloc(100*sizeof(data));
do {
printf(" ---------------- MARINE PRODUCT STOCK PROGRAM ---------------");
printf( " \n\nMAIN MENU :\n");
printf( "___________________________________________________________________\n\n");
printf( " 1. Input Product\n\n"); //data that the user input
printf( " 2. Entered History\n\n"); //show the history of the entered data by sorting the date
printf( " 3. Output Product\n\n"); //data that the user take out
printf( " 4. Exited Product\n\n");//show the history of the exited data by sorting the date
printf( " 5. Search Product\n\n"); //show the specific product by calling the code of the product
printf( " 6. Show All Product\n\n");
printf( " _____________________________\n\n");
printf( " choose (1 - 6) : ");
scanf ("%d", &menu);
if (menu < 1 || menu > 2) {
system("cls");
printf ("Please select the number between 1-2\n");
back_menu();
}
switch(menu) {
case 1:
input();
break;
case 2:
inputHistory();
break;
case 3:
output();
break;
case 4:
outHistory();
break;
// case 5:
// search(); // this function is used to search specific product by entering the code
// break;
// case 6:
// showAll(); // this function is used to show all of the stock in the warehouse. but the weight = input-output
// break;
}
free(innData);
free(outtData);
}
while (menu != 6);
system("cls");
printf ("============ Thankyou for using our program ============");
return 0;
}
void input(){
int code;
system ("cls");
printf("================= INPUT MENU =================\n\n");
printf("Enter the number of items to be recorded : "); scanf("%d", &amount);
printf( "_________________________________________________________________\n");
printf("\n Kode 0 = Fish \n kode 1 = Crab \n kode 2 = Squid \n kode 3 = Clam \n kode 4 = Lobster\n\t\t\t ");
for(i = 0; i < amount; i++){
printf("\n\nPRODUCT ORDER-%d",pointIn + 1);
printf("\n\tInput code\t : "); scanf(" %d", &code);
if(code < 0 || code > 4){
printf ("product with that number is not available, select number 0-4\n");
i--;
}
else {
strcpy( (innData+pointIn)->variety, variety[code]);
(innData+pointIn)->kode = code;
printf("\tvariety\t\t : %s\n", (innData+pointIn)->variety);
printf("\t Weight\t : "); scanf(" %d", &(innData+pointIn)->weight );
printf("\t Date (YYYYMMDD)\t : ");scanf(" %d", &(innData+pointIn)->date);
pointIn++;
}
}
back_menu();
}
void inputHistory(){
system("cls");
printf("***** INPUT STOCK DATE HISTORY ***** \n" );
printf("------------------------------------------------------------------\n");
printf("| DATE | CODE | NAME | WEIGHT | \n");
printf("------------------------------------------------------------------\n");
//call sort function here
for (i = 0; i < pointIn; i++){
printf(" %d %d %s %d \n", (innData+i)->date,(innData+i)->kode, (innData+i)->variety,(innData+i)->weight) ;
}
printf("------------------------------------------------------------------\n");
back_menu();
}
void output(){
int code;
system ("cls");
printf("================= INPUT MENU =================\n\n");
printf("Enter the number of items to be recorded : "); scanf("%d", &amount);
printf( "_________________________________________________________________\n");
printf("\n Kode 0 = Fish \n kode 1 = Crab \n kode 2 = Squid \n kode 3 = Clam \n kode 4 = Lobster\n\t\t\t ");
for(i = 0; i < amount; i++){
printf("\n\nPRODUCT ORDER-%d",pointOut + 1);
printf("\n\tInput code\t : "); scanf(" %d", &code);
if(code < 0 || code > 4){
printf ("product with that number is not available, select number 0-4\n");
i--;
}
else {
strcpy( (outtData+pointOut)->variety, variety[code]);
(outtData+pointOut)->kode = code;
printf("\tvariety\t\t : %s\n", (outtData+pointOut)->variety);
printf("\tWeight\t : "); scanf(" %d", &(outtData+pointOut)->weight );
printf("\tDate (YYYYMMDD)\t : ");scanf(" %d", &(outtData+pointOut)->date);
pointOut++;
}
}
back_menu();
}
void outHistory(){
system("cls");
printf("***** EXIT STOCK DATE HISTORY ***** \n" );
printf("------------------------------------------------------------------\n");
printf("| DATE | CODE | NAME | WEIGHT | \n");
printf("------------------------------------------------------------------\n");
//call sort function here
for (i = 0; i < pointIn; i++){
printf(" %d %d %s %d \n", (outtData+i)->date,(outtData+i)->kode, (outtData+i)->variety,(outtData+i)->weight) ;
}
printf("------------------------------------------------------------------\n");
back_menu();
}
void back_menu(){
printf("\n\n\t\t\tPress any key to continue.....");
getch();
system("cls");
}
This is my code and here I'm unable to manage the spaces in the header in my output when I was converting in table form.
Here is what I did :
#include <stdio.h>
int main()
{
int n;
printf("Enter no of students : ");
scanf("%d",&n);
int marks1[n], marks2[n],rollno[n];
float avg=0, total=0;
char name[5][10];
char grade;
for(int i=0; i<n; i++) {
printf("Enter name %d : ",(i+1));
scanf("%s",name[i]);
printf("Enter roll no : ");
scanf("%d",&rollno[i]);
printf("Enter Marks1 of student %d : ",(i+1));
scanf("%d",&marks1[i]);
printf("Enter marks2 of student %d : ",(i+1));
scanf("%d",&marks2[i]);
}
printf("\n Student Records \n");
printf("Name \t Roll No \t Marks1 \t Marks2 \t Total \t Avg \t Grade \n");
for(int i=0; i < n; i++) {
total = marks1[i] + marks2[i];
avg = (marks1[i] + marks2[i])/2;
if(avg >= 85) {
grade = 'S';
} else if (avg >=70 && avg < 85) {
grade = 'A';
} else if (avg < 70 && avg>=60) {
grade = 'B';
} else if (avg >= 50 && avg < 60) {
grade = 'C';
} else {
grade = 'F';
}
printf("%-8s | %-14d | %-14d | %-9d | %-7.2f | %-8.2f | %-7c\n", name[i], rollno[i], marks1[i], marks2[i], total, avg, grade);
avg=0;
total=0;
}
return 0;
}
Output:
Enter no of students : 1
Enter name 1 : raju
Enter roll no : 22
Enter Marks1 of student 1 : 78
Enter marks2 of student 1 : 98
Student Records
Name Roll No Marks1 Marks2 Total Avg Grade
raju | 22 | 78 | 98 | 176.00 | 88.00 | S
Is there any method to handle the spaces during Input ?
You are using tabs in your header, but explicit widths in the numerical output. It's up to the console how to print tabs. If you want more control over your output, use the same explicit widths for header and data.
For example:
// header
printf("%-8s | %-14s | %-14s | ...\n", "Name", "Roll No", "Marks");
// data rows
printf("%-8s | %-14d | %-14d | ...\n", name[i], rollno[i], marks[i]);
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 trying to create a function to enter x and o in my board which has counters to 1 - 9 already. Can someone explain me the algorithm and logic so i can try and code accordingly
If someone can guide me through, i am going through different examples but nothing specifically for shorter functions
//function to initialize board and my main and last is the function with printf commands
#include <stdio.h>
#define MAX 3
void InitializeBoard(int m, int n , char board[][n]){
int c =1;
for(int i =0; i<m; i++){
for(int j=0; j< n; j++){
board[i][j] = c+'0';
c++;
}
}
return;
}
void PrintBoard(int m, int n, char board[][n]){
printf("\n %c | %c | %c \n", board[0][0],
board[0][1], board[0][2]);
printf("\n--------------\n");
printf("\n %c | %c | %c \n", board[1][0],
board[1][1], board[1][2]);
printf("\n--------------\n");
printf("\n %c | %c | %c \n\n", board[2][0],
board[2][1], board[2][2]);
return;
}
int main() {
printf("Let's begin the game ! \n " );
char choice;
int m , n ;
char board [MAX][MAX] ;
do {
printf("Press 'p' to print the tic-tac-toe board.\n");
printf("Press 'c' to create the tic-tac-toe board with some X and O celss.\n");
printf("Press 't' to test is the tic-tac-toe board is valid or invalid.\n");
printf("Press 'w' to predict winning cell for the player X and O.\n\n");
printf("Press 'e' to exit\n");
scanf(" %c", &choice);
switch(choice){
case 'p' :
InitializeBoard(m,n,board);
PrintBoard(m,n, board);
break;
case 'c' :
default:
choice =-1;
}
}while(choice!=-1);
return 0;
}
I expect output
1|2|3
-----
4|5|6
-----
7|8|9
The problem is uninitialized variables which you are using to fill the board.
int m , n ;
......
InitializeBoard(m,n,board);
PrintBoard(m,n, board);
You need to initialize them to number of rows and columns.
int m = MAX , n = MAX;
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;
}