I am making a menu for a store with 4 options; add product, delete product, see table of created products and exit the program.
I finished the option to add products and exit, they both work fine.
Now I have to make the option to see the product table, supposedly I had already finished it but I noticed a problem ...
The first time I go in to see the product table, it prints it to me normally, like this.
enter image description here
But when I go to the menu and go back to the product table, it prints it like this.
enter image description here
Like I said, it only prints it right the first time I see it, then it prints it wrong.
Do you know how I can solve it?
This is the part of the code where I print the product table.
void table()
{
int c = k, m = 7;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 4;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
This is my complete code (maybe I have one or another library too many because I have been experimenting).
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
#include<ctype.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
struct products
{
int numor{},
cant{};
float preuni{},
subt{},
IVA{},
total{};
string cod{};
string descr{};
}product[51];
void add();
void intro_code();
int val_code(char codigo[]);
void table();
void gotoxy(int x, int y);
int i = 1; //Product No. (counter)
int k = 1; //Consecutive number (counter)
int main()
{
char opc;
cout << " Welcome ";
cout << endl;
cout << "\n1.- Add product.";
cout << "\n2.- Delete product.";
cout << "\n3.- Table of created products.";
cout << "\n4.- Exit";
cout << endl;
cout << "\nWhat do you want to do today?: "; cin >> opc;
switch (opc)
{
case '1':
system("cls");
cout << "\nAdd product";
add();
system("pause");
system("cls");
return main();
case '2':
cout << "\nDelete product";
system("cls");
return main();
case '3':
table();
return main();
case '4':
exit(EXIT_SUCCESS);
default:
system("cls");
cout << "Warning: the data entered is not correct, try again.\n\n";
return main();
}
return 0;
}
void add()
{
int can;
cout << "\nHow many products do you want to register?: "; cin >> can;
if (can <= 0 || can > 51)
{
system("cls");
cout << "Warning: The amount of products entered is not valid, try again";
return add();
}
for (int p = 1; p <= can;)
{
if (i < 51)
{
if (k <= 51) // In this part, consecutive numbers are generated automatically
{
cout << "\nNumber of order: ";
cout << k;
cout << endl;
product[i].numor = k;
k++;
}
cin.ignore();
cout << "Name of product: ";
getline(cin, product[i].descr);
intro_code();
cout << "Quantity to sell: "; cin >> product[i].cant;
cout << "unit price: $"; cin >> product[i].preuni;
product[i].subt = product[i].preuni * product[i].cant;
cout << "Subtotal: $" << product[i].subt;
product[i].IVA = product[i].subt * 0.16;
cout << "\nIVA: $" << product[i].IVA;
product[i].total = product[i].subt + product[i].IVA;
cout << "\nTotal price: $" << product[i].total;
cout << "\n-------------------------------------------------------------------------------";
cout << endl;
i++;
}
p++;
}
}
/*In this function the product code is entered, if the user enters a code
less than or greater than 5 characters the program displays an error message and allows the
user try again.*/
void intro_code()
{
char hello[10];
int xyz;
do {
cout << "Code of product (5 digits): ";
cin.getline(hello, 10, '\n');
if (strlen(hello) != 5)
{
cout << "The data entered is incorrect, try again ...";
cout << endl;
return intro_code();
}
else
{
xyz = val_code(hello);
}
} while (xyz == 0);
product[i].cod = hello;
}
/*As the requirement for "product code" is that it does not contain letters, special characters or blank spaces
create the function val_code to go through each character entered in the code, check character by character with the isdigit function
to see if the character is numeric or not, if it is not numeric it prints a warning message and allows the user to try again
without leaving the console.*/
int val_code(char hello[]) {
int abc;
for (abc = 0; abc < strlen(hello); abc++) {
if (!(isdigit(hello[abc]))) {
cout << "The data entered is incorrect, try again ...";
cout << endl;
return 0;
}
}
return 1;
}
void table()
{
int c = k, m = 7;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 4;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
void gotoxy(int x, int y)
{
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
Thank you very much in advance :)
The main reason for this problem is that after the size of the console changes, the position of the symbols you draw has also changed. At the same time, the line break determined by cout<<endl; also has a problem. For example, after the window becomes larger, the line length of the console becomes larger, but cout<<endl; is still the original line length.
However, there is no good solution. I suggest you directly set the console size and m=5, m=m+2.
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
#include<ctype.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
struct products
{
int numor{},
cant{};
float preuni{},
subt{},
IVA{},
total{};
string cod{};
string descr{};
}product[51];
void add();
void intro_code();
int val_code(char codigo[]);
void table();
void gotoxy(int x, int y);
int i = 1; //Product No. (counter)
int k = 1; //Consecutive number (counter)
int main()
{
HWND console = GetConsoleWindow();
RECT r;
GetWindowRect(console, &r);
MoveWindow(console, r.left, r.top, 1400, 400, TRUE);
char opc;
cout << " Welcome ";
cout << endl;
cout << "\n1.- Add product.";
cout << "\n2.- Delete product.";
cout << "\n3.- Table of created products.";
cout << "\n4.- Exit";
cout << endl;
cout << "\nWhat do you want to do today?: "; cin >> opc;
switch (opc)
{
case '1':
system("cls");
cout << "\nAdd product";
add();
system("pause");
system("cls");
return main();
case '2':
cout << "\nDelete product";
system("cls");
return main();
case '3':
table();
return main();
case '4':
exit(EXIT_SUCCESS);
default:
system("cls");
cout << "Warning: the data entered is not correct, try again.\n\n";
return main();
}
return 0;
}
void add()
{
int can;
cout << "\nHow many products do you want to register?: "; cin >> can;
if (can <= 0 || can > 51)
{
system("cls");
cout << "Warning: The amount of products entered is not valid, try again";
return add();
}
for (int p = 1; p <= can;)
{
if (i < 51)
{
if (k <= 51) // In this part, consecutive numbers are generated automatically
{
cout << "\nNumber of order: ";
cout << k;
cout << endl;
product[i].numor = k;
k++;
}
cin.ignore();
cout << "Name of product: ";
getline(cin, product[i].descr);
intro_code();
cout << "Quantity to sell: "; cin >> product[i].cant;
cout << "unit price: $"; cin >> product[i].preuni;
product[i].subt = product[i].preuni * product[i].cant;
cout << "Subtotal: $" << product[i].subt;
product[i].IVA = product[i].subt * 0.16;
cout << "\nIVA: $" << product[i].IVA;
product[i].total = product[i].subt + product[i].IVA;
cout << "\nTotal price: $" << product[i].total;
cout << "\n-------------------------------------------------------------------------------";
cout << endl;
i++;
}
p++;
}
}
/*In this function the product code is entered, if the user enters a code
less than or greater than 5 characters the program displays an error message and allows the
user try again.*/
void intro_code()
{
char hello[10];
int xyz;
do {
cout << "Code of product (5 digits): ";
cin.getline(hello, 10, '\n');
if (strlen(hello) != 5)
{
cout << "The data entered is incorrect, try again ...";
cout << endl;
return intro_code();
}
else
{
xyz = val_code(hello);
}
} while (xyz == 0);
product[i].cod = hello;
}
/*As the requirement for "product code" is that it does not contain letters, special characters or blank spaces
create the function val_code to go through each character entered in the code, check character by character with the isdigit function
to see if the character is numeric or not, if it is not numeric it prints a warning message and allows the user to try again
without leaving the console.*/
int val_code(char hello[]) {
int abc;
for (abc = 0; abc < strlen(hello); abc++) {
if (!(isdigit(hello[abc]))) {
cout << "The data entered is incorrect, try again ...";
cout << endl;
return 0;
}
}
return 1;
}
void table()
{
int c = k, m = 5;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 2;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
void gotoxy(int x, int y)
{
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
In addition, it is not recommended that you use cmd to make gui.
Related
I'm just starting in studying C++, and I am doing a simple challenge which is GWA Calculator, but I am having a problem finding out how to store the multiple strings input (which is the Subjects/Course) and displaying it after together with the Units and Grades. I am really sorry, but I tried finding out how and I couldn't find an answer. Hope you can help me out.
#include <stdlib.h>
using namespace std;
void calculateGWA();
int main()
{
system("cls");
int input;
cout << "\t\t -------------------------------------------------------------------------- " << endl;
cout << "\t\t| GWA Calculator |" << endl;
cout << "\t\t -------------------------------------------------------------------------- " << endl;
cout << "\t\t| MENU:\t\t\t\t\t\t\t " << "|" << endl;
cout << "\t\t| 1. Calculate GWA (General Weighted Average)\t\t " << "|" << endl;
cout << "\t\t| 2. Calculate CGWA (Cummulative Weighted Average) " << "|" << endl;
cout << "\t\t| 4. Exit Application\t\t\t\t\t " << "|" << endl;
cout << "\t\t| |" << endl;
cout << "\t\t -------------------------------------------------------------------------- " << endl;
sub:
cout << "\t\tEnter your choice: ";
cin >> input;
switch(input)
{
case 1:
calculateGWA();
break;
case 2:
//calculateCGPA();
break;
case 3:
main();
break;
case 4:
exit(EXIT_SUCCESS);
break;
default:
cout << "You have entered wrong input.Try again!\n" << endl;
goto sub;
break;
}
}
void calculateGWA()
{
int q;
system("cls");
cout << "-------------- GWA Calculator -----------------"<<endl;
cout << " How many course(s)?: ";
cin >> q;
char c_name[50];
float unit [q];
float grade [q];
cout << endl;
for(int i = 0; i < q; i++)
{
cout << "Enter the Course Name " << i+1 << ": ";
cin >> c_name;
cout << "Enter the Unit " << c_name << ": ";
cin >> unit[i];
cout << "Enter the Grade " << c_name << ": ";
cin >> grade[i];
cout << "-----------------------------------\n\n" << endl;
}
float sum = 0;
float tot;
for(int j = 0; j < q; j++)
{
tot = unit[j] * grade[j];
sum = sum + tot;
}
float totCr = 0;
for(int k = 0; k < q; k++)
{
totCr = totCr + unit[k];
}
system("cls");
// PRINTS OUT THE COURSES - UNITS - GRADES AND GWA //
cout << "\t\t =============================================================== " << endl;
cout << "\t\t| COURSE | UNIT | GRADE |" << endl;
cout << "\t\t =============================================================== " << endl;
cout << "Total Points: " << sum << " \n Total Credits: " << totCr << " \nTotal GPA: " << sum/totCr << " ." << endl;
cout << c_name << "\n" << endl;
cout << "===================================" << endl;
sub:
int inmenu;
cout << "\n\n\n1. Calculate Again" << endl;
cout << "2. Go Back to Main Menu" << endl;
cout << "3. Exit This App \n\n" << endl;
cout << "Your Input: " << endl;
cin >> inmenu;
switch(inmenu)
{
case 1:
calculateGPA();
break;
case 2:
main();
break;
case 3:
exit(EXIT_SUCCESS);
default:
cout << "\n\nYou have Entered Wrong Input!Please Choose Again!" << endl;
goto sub;
}
}
so I have a school project where I'm trying to create a bank account. So I have an array of class customer containing the customer name etc, this customer can have multiple accounts, so I have created an array of class accounts inside of customer. My problem is, I can't call a getter function inside of the account array, I have tried using customerArray[curr_id]->accountArray[curr_acc_num]->get_balance() however I am getting an error telling my that it is unaccessable.
Here is the code, any input would be apprechiated as it is still a work in progress.
#include <iostream>.
#include <windows.h>
#include "account.h"
#include "customer.h"
using namespace std;
bool quit;
int amount;
double bal;
bool valid_pin;
customer* customerArray[200];
account* accountArray[5];
int curr_id;
int curr_acc_num;
//1st name, 2nd name, ID
customer cust1("Paul", "Smith", 2233);
//ID, Deposit, Pin
account Paul(112, 222, 6716);
//Welcome screen function
void welcome_screen() {
cout << endl << endl << endl;
cout << "\tAbertay Banking" << endl;
cout << "\t System " << endl << endl << endl;
Sleep(1800);
}
//Display account balance function
void account_balance() {
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << " " << customerArray[curr_id]->get_name() << endl;
cout << " ID: " << customerArray[curr_id]->get_custid() << endl << endl;
cout << " Balance: " << char(156) << customerArray[curr_id]->accountArray[curr_acc_num]->get_balance() << endl;
//Display any outstanding loans
if (Paul.get_loan() > 0) {
cout << endl << endl;
cout << " Outstanding loan: -" << char(156) << Paul.get_loan();
Sleep(3000);
}
//User has no loan on this account
else {
Sleep(3000);
}
}
//Withdrawl function
void withdrawl() {
bal = Paul.get_balance();
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "Enter the amount you wish to withdraw: ";
cin >> amount;
//customer has sufficent funds, withdrawl accepted
if (amount <= bal + Paul.get_overdraft()) {
bal -= amount;
Paul.set_balance(bal);
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl; cout << "You have withdrawn: " << char(156) << amount << endl;
cout << "You now have a balance off: " << char(156) << bal << endl;
cout << "Do you wish to carry out another transaction?"; //do you wish to carry out another transaction.
Sleep(2000);
}
//customer doesn't have enough funds to carry out withdrawl
else {
char choice;
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "You have insufficient funds in your account" << endl;
}
}
//Deposit function
void deposit() {
//balance from user account
bal = Paul.get_balance();
char check;
double ln;
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "Enter the amount you wish to deposit: ";
cin >> amount;
//Option to pay off loan, if applicable
if (Paul.get_loan() > 0) {
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "Do you want to pay off your loan? (Y/N)" << endl;
cin >> check;
system("cls");
cout << "\tBank of Abertay" << endl << endl;
//User selected to pay off loan
if (check == 'y') {
//deposit paid into loan
if (amount < Paul.get_loan()) {
ln = Paul.get_loan() - amount;
Paul.set_loan(ln);
cout << "Your loan is now at: -" << char(156) << Paul.get_loan() << endl;
}
//loan is payed of, any extra money is deposited into balance
else {
ln = amount - Paul.get_loan() + Paul.get_balance();
Paul.set_loan(0);
Paul.set_balance(ln);
cout << "You have payed your loan off!" << endl;
}
}
}
//user has no loan or doesn't wish to pay off loan
else {
bal += amount;
Paul.set_balance(bal);
}
cout << "You have deposited: " << char(156) << amount << endl;
cout << "You now have a balance off: " << char(156) << bal << endl;
cout << "Would you like to select another option with this account?"; //do you wish to carry out another transaction.
Sleep(1500);
}
//Apply for overdraft
void overdraft() {
system("cls");
char choice;
cout << endl << endl;
cout << "\tTake out an overdraft of " << char(156) << "300? " << endl;
cout << "\t (Y/N)" << endl;
cin >> choice;
if (choice == 'y') {
Paul.set_overdraft(300);
}
}
//Calculating interest rates
double interest_rate(int loan) {
//Up to £3,000 rate of 11%
if (loan < 3000) {
return 1.11;
}
//From £3,000 to £7,000 rate of 9%
else if (loan > 3000 && loan < 7000) {
return 1.09;
}
//From £7,000 to £21,000 rate of 7%
else if (loan > 7000 && loan < 21000) {
return 1.07;
}
//From £21,000 over rate of 5%
else if (loan < 21) {
return 1.05;
}
}
//Loan eligibility funcition
void loan_elgibility() {
double max_loan;
double loan;
//Calculating loan eligibility
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "Caculating loan eligibility";
max_loan = (2 * Paul.get_balance());
Sleep(800);
//Loan and rates
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << " You are eligible to borrow up to: " << char(156) << max_loan << endl << endl;
cout << " Interest rates are as follows" << endl << endl;
cout << " - " << char(156) << "3,000 at 11%" << endl;
cout << " " << char(156) << "3,000 - " << char(156) << "7,000 at 9%" << endl;
cout << " " << char(156) << "7,000 - " << char(156) << "21,000 at 7%" << endl;
cout << " " << char(156) << "21,000 - at 5%" << endl;
Sleep(6200);
//User input loan request
system("cls");
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << " Enter loan request: " << char(156);
cin >> loan;
//Processing loan request
system("cls");
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << " We are processing your request..." << endl;
Sleep(800);
system("cls");
//Loan has been approved, loan deposited into account
if (loan <= Paul.get_balance()) {
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << "Your loan has been approved" << endl;
bal = Paul.get_balance() + loan;
loan = interest_rate(loan) * loan;
Paul.set_balance(bal);
Paul.set_loan(loan);
Sleep(800);
}
//Loan has not been approved
else {
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << "You do not qualify for a loan of this amount";
Sleep(800);
}
}
//Quit function
void quit_screen() {
system("cls");
char choice;
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << " Do you want to quit? (Y/N) " << endl;
cout << " ";
cin >> choice;
// customer wants to quit, end while loop and program
if (choice == 'y') {
system("cls"); //clear screen
cout << endl << endl << endl;
cout << " Thanks for using," << endl;
cout << " Bank of Abertay!"<< endl;
Sleep(2000);
quit = true;
}
else {
quit = false;
}
}
//Request user pin number
bool pin_request() {
double pin;
int counter = 0;
do {
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "\tEnter pin: ";
cin >> pin;
if (pin == Paul.get_pin()) {
return true;
}
else if (counter == 3) {
cout << "You have entered an invalid pin too many times!";
Sleep(800);
return false;
}
else {
system("cls");
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << "You have entered an invalid pin" << endl;
Sleep(800);
valid_pin = false;
counter++;
}
} while (valid_pin == false && counter < 3);
}
//Adding a new customer
int counter = 0;
void add_customer(string first_nom, string second_nom, int cust_ID) {
customer* new_customer = new customer(first_nom, second_nom, cust_ID);
customerArray[counter] = new_customer;
counter++;
}
//creating new bank account
void create_account()
{
int input_custid;
double input_balance;
int input_pin;
string first_nom;
string second_nom;
int cust_ID;
char choice;
//Request new customer information
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "Enter first name: ";
cin >> first_nom;
cout << endl;
cout << "Enter surname: ";
cin >> second_nom;
cout << endl;
cout << "Customer ID: ";
cin >> cust_ID;
//create new customer class array
add_customer(first_nom, second_nom, cust_ID);
//creating new account array
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "Enter The account No. :";
cin >> input_custid;
cout << "Initial deposit in new account: ";
cin >> input_balance;
cout << "Create pin: ";
cin >> input_pin;
system("cls");
cout << " We are processing your request..." << endl;
Sleep(800);
cust1.add_account(input_custid, input_balance, input_pin);
system("cls");
cout << "Account Created.." << endl;
cout << "Thank you for joining the Bank of Abertay";
Sleep(800);
}
//find user account
bool find_account() {
int custID;
int counter;
bool found_account;
system("cls");
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << " Enter your customer ID: ";
cin >> custID;
cout << " - ";
cin >> curr_acc_num;
//not happy about this!!
for (int i = 0; i < 200; i++) {
if (customerArray[i]->get_custid() == custID) {
curr_id = i;
return true;
}
else if (i == 199) {
return false;
}
}
}
//an option to send money to another account?
// need a function that takes user back to option menu if wrong pin enter!
int main() {
//welcome screen
welcome_screen();
//while loop until player decides to quit
do {
int option_choice;
system("cls"); //clear screen, updating board every time function called
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "\t Menu" << endl << endl;
cout << "\t1. View Balance" << endl;
cout << "\t2. Withdraw" << endl;
cout << "\t3. Deposit" << endl;
cout << "\t4. Loan eligibility" << endl;
cout << "\t5. New account" << endl;
cout << "\t6. Overdraft" << endl;
cout << "\t7. Quit" << endl << endl;
cout << "\t\tSelect: ";
cin >> option_choice;
//ensure option screen only runs through once unless an invalid option is chosen
int valid_number_check = 0;
// do {
switch (option_choice) {
//Display account balance
case 1:
if (find_account() == true && pin_request() == true) {
account_balance();
break;
}
else {
cout << "Your request has been denied";
break;
}
//Account withdrawl
case 2:
if ( find_account() == true && pin_request() == true) {
withdrawl();
break;
}
else {
cout << "Your request has been denied";
break;
}
//Account deposit
case 3:
if (find_account() == true && pin_request() == true) {
deposit();
break;
}
else {
cout << "Your request has been denied";
break;
}
//Loan eligibility
case 4:
if (find_account() == true && pin_request() == true) {
loan_elgibility();
break;
}
else {
cout << "Your request has been denied";
break;
}
//Create new account
case 5:
create_account();
break;
//Overdraft
case 6:
if (find_account() == true && pin_request() == true) {
overdraft();
break;
}
else {
cout << "Your request has been denied";
break;
}
//Quit
case 7:
quit_screen();
break;
//Invalid number entered
default:
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << "Please enter a valid number";
Sleep(800);
break;
}
} while (quit == false);
}
// main
Account .h
#pragma once
#include <string>
#include "account.h"
using namespace std;
class customer
{
private:
int custid;
string name;
account* accountArray[5];
int counter = 0;
public:
int get_custid();
customer(string, string, int);
string get_name();
void add_account(int, double, int);
~customer();
};
Account.cpp
#include "customer.h"
#include "account.h"
#include <string>
using namespace std;
customer::customer(string first_nom, string second_nom, int cust_ID) {
counter++;
string first_name = first_nom;
string sur_name = second_nom;
//counting the number of accounts
counter++;
//identification of customer array
//custid = counter + 1000;
custid = cust_ID;
}
customer::~customer()
{
}
int customer::get_custid() {
return custid;
}
void customer::add_account(int id, double dep, int pin) {
account* new_account = new account(id, dep, pin);
accountArray[counter] = new_account;
counter++;
}
string customer::get_name() {
return name;
}
customer.h
#pragma once
class account
{
private:
double balance;
int custid;
double loan_amount;
double overdraft;
int pin;
int account_number;
public:
account(int, double, int);
~account();
//getters
double get_balance();
double get_loan();
double get_pin();
double get_overdraft();
//setters
void set_overdraft(double over);
void set_balance(double bal);
void set_loan(double loan);
};
customer.cpp
#include "account.h"
#include <iostream>
#include <windows.h>
using namespace std;
account::account(int input_custid, double input_balance, int input_pin)
{
custid = input_custid;
balance = input_balance;
pin = input_pin;
loan_amount = 0;
overdraft = 0;
}
account::~account()
{
}
double account::get_balance()
{
return balance;
}
double account::get_loan()
{
return loan_amount;
}
double account::get_pin()
{
return pin;
}
double account::get_overdraft()
{
return overdraft;
}
void account::set_balance(double bal)
{
balance = bal;
}
void account::set_loan(double loan)
{
loan_amount = loan;
}
void account::set_overdraft(double over)
{
overdraft = over;
}
I was able to write a program to pass my c++ class in college except for one feature. I was unable to create a function that sorted the names inside an array of structs with name of type char alphabetically. Please advise on how to tackle this problem.
I would need a function that sorts the accountRecords array alphabetically.
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
//Structure Initilizations
const int NAME_SIZE = 25, ADDR_SIZE = 100, CITY_SIZE = 51, STATE_SIZE = 4, DATE_SIZE = 16, CUSTOMER_ID = 10, TRANSACTION_TYPE = 16;
struct MasterRecord
{
int customerID;
char name[NAME_SIZE]; // SORT THIS FIELD ALPHABETICALLY
char address[ADDR_SIZE];
char city[ADDR_SIZE];
char state[STATE_SIZE];
char zip[STATE_SIZE];
float accountBalance;
char lastTransactionDate[15];
};
struct TransactionRecord
{
int customerID;
char transactionType;
float amount;
char transactionDate[15];
};
//File Array Initializations
vector<MasterRecord> masterRecordList(101);
vector<TransactionRecord> transRecordList(101);
//Array List Record Position
int masterRecordArrayPosition = 0;
int transactionRecordArrayPosition = 0;
//User Menu Answer Variable Initialization
int userAnswer = 0;
string recordNotFoundAnswer = "";
//Print Function Prototypes
void showMenu();
void showMasterRecord(int);
void showTransactionRecord(int);
//Main Menu Function Prototypes
void newCustomerRecord(int);
void editCustomerRecord(int);
void deleteCustomerRecord(int);
int randomComputerID();
int searchMasterRecord(int);
void saveAccountRecords();
void saveTransRecords();
void newTransactionRecord(int);
//Placeholders Variables
int customerIDsearch = 0;
int customerIDSearchArrayPosition = 0;
int userNameCharactererror = 0;
//Function Loop Counters
int accountWriteCounter = 0;
int transWriteCounter = 0;
int showRecordCounter = 0;
int showTransCounter = 0;
//System time Declaration and Conversion for [lastTransactionDate]
time_t now = time(0);
tm *ltm = localtime(&now);
string currentYearInString = to_string(1900 + ltm->tm_year);
string currentMonthInString = to_string(1 + ltm->tm_mon);
string currentDayInString = to_string(ltm->tm_mday);
string currentDateInString = currentMonthInString + "/" + currentDayInString + "/" + currentYearInString;
char dateInChar[15];
//Main Program
int main()
{
//Final conversion of time in string to char for storage
strncpy_s(dateInChar, currentDateInString.c_str(), 15);
//Open MasterRecord file and read records to arrays
fstream masterRecord("masterRecord.dat", ios::in | ios::binary);
int listCounter = 0;
if (!masterRecord) {
cout << "Unable to open the user records file, creating file database....Done!" << endl;
masterRecord.open("masterRecord.dat", ios::out | ios::binary);
}
else {
while (!masterRecord.eof()) {
masterRecord.read(reinterpret_cast<char *>(&masterRecordList[listCounter]), sizeof(masterRecordList[0]));
if (masterRecordList[listCounter].customerID != 0) {
listCounter++;
}
masterRecordArrayPosition = listCounter;
}
masterRecord.close();
}
//Open Transaction Record and read to arrays
fstream transactionRecord("transactionRecord.dat", ios::in | ios::binary);
int listCounter2 = 0;
if (!transactionRecord) {
cout << "Unable to open the transaction file, creating file database....Done!" << endl << endl;
transactionRecord.open("transactionRecord.dat", ios::out | ios::binary);
}
else {
while (!transactionRecord.eof()) {
transactionRecord.read(reinterpret_cast<char *>(&transRecordList[listCounter2]), sizeof(transRecordList[0]));
if (transRecordList[listCounter2].customerID != 0) {
listCounter2++;
}
transactionRecordArrayPosition = listCounter2;
}
transactionRecord.close();
}
//Time Declaration Used to Generate Random IDs
srand((unsigned)time(0));
//Main user Program Loop
while (userAnswer != 6) {
showMenu();
cin >> userAnswer; cout << endl;
//Menu Input Data Validation
if (cin.fail()) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
cin.clear();
cin.ignore();
}
else {
if (userAnswer < 1 || userAnswer > 7) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
userAnswer = 0;
}
}
//Menu Selection Switch Case
switch (userAnswer) {
case 1:
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
break;
case 2:
newTransactionRecord(transactionRecordArrayPosition);
break;
case 3:
cout << "Please enter the Customer ID you would like to Delete" << endl << endl; //[Delete Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
deleteCustomerRecord(customerIDSearchArrayPosition);
}
break;
case 4:
cout << "Please enter the Customer ID you would like to edit." << endl << endl; //[Search/Edit Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
editCustomerRecord(customerIDSearchArrayPosition);
}
else {
cout << "Record was not found, would you like to add a new record? Y = Yes, N = No" << endl << endl;
cin >> recordNotFoundAnswer;
if (recordNotFoundAnswer == "Y" | recordNotFoundAnswer == "y") {
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
}
else if (recordNotFoundAnswer == "N" | recordNotFoundAnswer == "n") {
userAnswer = 0;
}
}
break;
case 5:
cout << setw(212) << "Please find all customer records in the database" << endl << endl; //[Show all Records] Function goes here
cout << setw(40) << "Name:" << setw(10) << "ID:" << setw(23) << "Street Address:" <<setw(10) << "ZIP:" << setw(16) << "L.Trans Date:" << setw(11) << "Balance: " << endl;
while (showRecordCounter < 100) {
if (masterRecordList[showRecordCounter].customerID != 0) {
showMasterRecord(showRecordCounter);
}
showRecordCounter = showRecordCounter + 1;
} showRecordCounter = 0;
userAnswer = 0;
cout << endl;
break;
case 6:
cout << "Saving changes to database...Done!" << endl;
saveAccountRecords();
saveTransRecords();
cout << "Done!" << endl;
break;
case 7:
cout << "Showing all transaction Records:" << endl << endl;
while (showTransCounter < 100) {
if (transRecordList[showTransCounter].customerID != 0) {
showTransactionRecord(showTransCounter);
}
showTransCounter = showTransCounter + 1;
} showTransCounter = 0;
userAnswer = 0;
break;
}
}
return 0;
}
//Databas Management Functions
void saveAccountRecords() {
fstream masterRecord("masterRecord.dat", ios::out | ios::binary);
while (accountWriteCounter < 100) {
masterRecord.write(reinterpret_cast<char *>(&masterRecordList[accountWriteCounter]), sizeof(masterRecordList[0]));
accountWriteCounter++;
}
masterRecord.close();
}
void saveTransRecords() {
fstream transRecord("transactionRecord.dat", ios::out | ios::binary);
while (transWriteCounter < 100) {
transRecord.write(reinterpret_cast<char *>(&transRecordList[transWriteCounter]), sizeof(transRecordList[0]));
transWriteCounter++;
}
transRecord.close();
}
//Random Function
int randomComputerID() {
int randomNumber;
randomNumber = (rand() % 1000) + 10000;
return randomNumber;
}
//Program Print Functions
void showMenu() {
cout << "Welcome to your C++ company terminal! Please enter one of the options below to continue." << endl << endl;
cout << "1. New Customer Record" << endl;
cout << "2. New Transaction Record" << endl;
cout << "3. Delete Customer Record" << endl;
cout << "4. Edit Customer Record" << endl;
cout << "5. Show all Account Records in Database" << endl;
cout << "6. Exit and Save Changes to Database" << endl << endl;
cout << "Please enter the number for the correspondent action you would like to perform:" << endl;
}
void showMasterRecord(int arrayNum) {
cout << setw(40)
<< masterRecordList[arrayNum].name << setw(10) << masterRecordList[arrayNum].customerID << setw(23)
<< masterRecordList[arrayNum].address << setw(10)
<< masterRecordList[arrayNum].zip << setw(16)
<< masterRecordList[arrayNum].lastTransactionDate << setw(6) <<"$"
<< masterRecordList[arrayNum].accountBalance; cout << endl;
}
void showTransactionRecord(int arrayNum) {
cout << "Customer ID: " << transRecordList[arrayNum].customerID << endl;
cout << "Amount: $" << transRecordList[arrayNum].amount << endl;
cout << "Transaction Type: " << transRecordList[arrayNum].transactionType << endl;
cout << "Transaction Date: " << transRecordList[arrayNum].transactionDate << endl << endl;
}
//Main Menu Functions [Please insert your functions here and prototype them above].
void newCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
masterRecordList[arrayNum].customerID = randomComputerID();
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
do
{
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 25);
if (cin.fail()) {
cout << endl << "Please enter only characters up 25 chracters for your name." << endl;
userNameCharactererror = 1;
cin.clear();
cin.ignore(80, '\n');
}
else {
userNameCharactererror = 0;
}
} while (userNameCharactererror == 1);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Opening Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
masterRecordArrayPosition = masterRecordArrayPosition + 1;
}
void editCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 51);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Edit Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
}
void deleteCustomerRecord(int arrayNum) {
if (masterRecordList[arrayNum].accountBalance == 0)
{
masterRecordList[arrayNum].customerID = 0;
cout << "Record has been deleted" << endl << endl;
}
else {
cout << "Unable to delete record, customer accounts holds a positive balance" << endl << endl;
}
}
int searchMasterRecord(int customerID) //Search by customer name and returns array position
{
int arrayPosition = 0;
int arrayCounter = 0;
int customerIdPlaceholder = 0;
while (arrayCounter < 100) {
customerIdPlaceholder = masterRecordList[arrayCounter].customerID;
if (customerIdPlaceholder == customerID) {
cout << "Record has been found!" << endl << endl;
arrayPosition = arrayCounter;
arrayCounter = 100;
}
else {
arrayPosition = 9999;
}
arrayCounter = arrayCounter + 1;
}
return arrayPosition;
};
void newTransactionRecord(int arrayNum) {
// Request customer ID and transaction type from the user
cout << "Customer ID: ";
cin >> transRecordList[arrayNum].customerID;
cin.ignore();
cout << "Date: ";
strncpy_s(transRecordList[arrayNum].transactionDate, dateInChar, 15);
cout << transRecordList[arrayNum].transactionDate << endl;
cout << "Transaction Type [D = Deposit] [W = Withdrawal]: ";
cin >> transRecordList[arrayNum].transactionType;
cout << "Amount: $";
cin >> transRecordList[arrayNum].amount;
//Search for customer account, update balance, and assign last transaction date
customerIDSearchArrayPosition = searchMasterRecord(transRecordList[arrayNum].customerID);
if (customerIDSearchArrayPosition != 9999) {
if (transRecordList[arrayNum].transactionType == 'D') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance + transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Deposit Successful! " << endl << endl;
}
else if (transRecordList[arrayNum].transactionType == 'W') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance - transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Withdrawl Successful" << endl << endl;
}
}
else {
cout << "Customer account record was not found, transaction was not saved." << endl << endl;
}
transactionRecordArrayPosition = transactionRecordArrayPosition + 1;
}
Something along these lines:
std::sort(masterRecordList.begin(),
masterRecordList.begin() + masterRecordArrayPosition,
[](const MasterRecord& l, const MasterRecord& r) {
return strcmp(l.name, r.name) < 0;
});
this is an update to show chages, details below.
here is a link to snap shot of output
https://dl.dropboxusercontent.com/u/34875891/wrongoutput.PNG
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
using namespace std;
//create HotelRoom class
class HotelRoom
{
private:
char* ptr_guest;
char room_number[3];
int room_capacity;
int occupancy_status;
double daily_rate;
public:
HotelRoom(char roomNumber[], int roomCapacity, double roomRate, char* ptr_name, int occupancyStatus);
~HotelRoom();
void Display_Number();
void Display_Guest();
int Get_Capacity();
int Get_Status();
double Get_Rate();
int Change_Status(int);
double Change_Rate(double);
};
HotelRoom::HotelRoom(char roomNumber[], int roomCapacity, double roomRate, char* ptr_name, int occupancyStatus)
{
strcpy(room_number, roomNumber);
room_capacity = roomCapacity;
daily_rate = roomRate;
ptr_guest = new char[strlen(ptr_name) + 1];
strcpy(ptr_guest, ptr_name);
occupancy_status = occupancyStatus;
}
HotelRoom::~HotelRoom()
{
cout << endl;
cout << "Destructor Executed";
cout << endl;
delete [] ptr_guest;
}
void HotelRoom::Display_Guest()
{
char* temp = ptr_guest;
while(*temp != '\0')
cout << *temp++;
}
void HotelRoom::Display_Number()
{
cout << room_number;
}
int HotelRoom::Get_Capacity()
{
return room_capacity;
}
int HotelRoom::Get_Status()
{
return occupancy_status;
}
double HotelRoom::Get_Rate()
{
return daily_rate;
}
int HotelRoom::Change_Status(int roomStatus)
{
if(roomStatus <= room_capacity )
{
occupancy_status = roomStatus;
return occupancy_status;
}
else
occupancy_status = -1;
}
double HotelRoom::Change_Rate(double newRate)
{
daily_rate = newRate;
return daily_rate;
}
int main()
{
cout << setprecision(2)
<< setiosflags(ios::fixed)
<< setiosflags(ios::showpoint);
//Declare variables to hold data
char roomNumber[3] = {'1','3','\0'};
char guestName[20];
double roomRate = 89.00;
int roomCapacity = 4;
int occupancyStatus = 0;
int status;
int checkOut;
int newCustomer;
//Ask for user input
cout << "What is the guest's name: ";
cin.getline(guestName, 20);
cout << endl;
cout << "How many guests will be staying in the room: ";
cin >> status;
HotelRoom HotelRoom1(roomNumber, roomCapacity, roomRate, guestName, status);
//Display Rooom information
cout << endl;
cout << endl;
if(HotelRoom1.Change_Status(status))
{
cout << endl;
cout << "Guest's Name: ";
HotelRoom1.Display_Guest();
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity() << endl;
cout << endl;
cout << "There are " << HotelRoom1.Get_Status() << " guests staying in the room";
}
cout << endl;
cout << endl;
cout << "Your room number is " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The rate for this room is " << HotelRoom1.Get_Rate();
cout << endl;
cout << endl;
//chech this guest out?
cout << "Check this guest out? ('1 = yes' '0' = no) ";
cin >> checkOut;
switch(checkOut)
{
case 1:
HotelRoom1.Change_Status(0);
for(int i = 0; i < 3; ++i )
{
cout << endl;
}
cout << "You have checked out of room number " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity();
cout << endl;
cout << endl;
cout << "There are currently " << HotelRoom1.Get_Status() << " occupants";
cout << endl;
cout << endl;
cout << "The rate of this room was " << HotelRoom1.Get_Rate();
break;
}
//check in new guest?
cout << endl;
cout << endl;
cout << "Check in new guest? ('1 = yes' '0' = no) ";
cin >> newCustomer;
for(int i = 0; i < 3; ++i )
{
cout << endl;
}
switch (newCustomer)
{
case 1:
HotelRoom HotelRoom2(roomNumber, roomCapacity, roomRate, guestName, status);
HotelRoom1.Change_Rate(175.00); //Change rate of room
cout << endl;
cout << "What is the guest's name: ";
cin.getline(guestName, 20);
cout << endl;
cout << "How many guests will be staying in the room: ";
cin >> status;
cout << endl;
cout << endl;
//Display new guest information
if(HotelRoom1.Change_Status(status))
{
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity() << endl;
cout << endl;
cout << "There are " << HotelRoom1.Get_Status() << " guests staying in the room";
}
cout << endl;
cout << endl;
cout << "Your room number is " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The rate for this room is " << HotelRoom1.Get_Rate();
cout << endl;
cout << endl;
break;
}
cout << endl;
system("PAUSE");
return 0;
}
this is an update to show chages, details below.
here is a link to snap shot of output
https://dl.dropboxusercontent.com/u/34875891/wrongoutput.PNG
char HotelRoom::Display_Guest()
{
cout << ptr_guest;
}
string HotelRoom::Display_Number()
{
cout << room_number;
}
int HotelRoom::Change_Status(int roomStatus)
{
if(roomStatus <= room_capacity )
{
occupancy_status = roomStatus;
return occupancy_status;
}
else
occupancy_status = -1;
}
These functions claim to be returning values. The first two are not, the last is not under certain conditons. Calling the first two is undefined behavior. Calling Change_Status with roomStatus > room_capacity is also undefined behavior.
There may be other problems with the code, but the elephant in the room is the undefined behavior. Any other debugging while you have undefined behavior is theoretically a waste of time.
I have started with C++ and I am in the middle of creating a hangman game, My code worked fine up until I chose to make three different levels of difficulty, My game asks the user for the difficulty level they would like to play, then instead of actually playing the game, it skips straight to the end where it says the user has guessed the word correctly. Any help appreciated!
The code is as follows :
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cctype>
using namespace std;
void ClearScreen();
void DisplayMan0();
void DisplayMan1();
void DisplayMan2();
void DisplayMan3();
void DisplayMan4();
void DisplayMan5();
void DisplayMan6();
void DisplayMan7();
int main()
{
const int MAX_WRONG = 7; // incorrect guesses allowed
void (*pfnaDisplayMan[])() = {DisplayMan0, DisplayMan1, DisplayMan2, DisplayMan3, DisplayMan4, DisplayMan5, DisplayMan6, DisplayMan7};
vector<string> words; // Level 1
words.push_back("GREEN");
words.push_back("BANANA");
words.push_back("LAPTOP");
words.push_back("GIRAFFE");
words.push_back("PENCIL");
vector<string> wordsD1; // Level 2
wordsD1.push_back("DELICIOUS");
wordsD1.push_back("COMPUTING");
wordsD1.push_back("SOFTWARE");
wordsD1.push_back("HARDWARE");
wordsD1.push_back("TELEPHONE");
vector<string> wordsD2; // Level 3
wordsD2.push_back("BAMBOOZLED");
wordsD2.push_back("DAYDREAMER");
wordsD2.push_back("CANNIBALISM");
wordsD2.push_back("NERVOUSLY");
wordsD2.push_back("APPROACHING");
srand((unsigned int)time(0));
string THE_WORD;
string soFar;
int wordLength;
string used; // letters already guessed
cout << "\t\t HANGMAN\n";
cout << "Please enter a difficulty level [1-3] ";
int dif = 0;
while(dif < 1 || dif > 3)
{
cin >> dif;
}
cout << "You have chosen difficulty level : "<< dif << endl;
if(dif == 1)
{
random_shuffle(words.begin(), words.end());
int incorrectGuesses = 0; // number of incorrect guesses
string const THE_WORD = words[0]; // word to guess
string soFar(THE_WORD.size(), '*'); // word guessed so far
// count length of randomly chosen string and display it
wordLength = THE_WORD.length();
}
if(dif == 2)
{
random_shuffle(wordsD1.begin(), wordsD1.end());
int incorrectGuesses = 0; // number of incorrect guesses
string const THE_WORD = wordsD1[0];
string soFar(THE_WORD.size(), '*');
wordLength = THE_WORD.length();
}
if(dif == 3)
{
random_shuffle(wordsD2.begin(), wordsD2.end());
int incorrectGuesses = 0; // number of incorrect guesses
string const THE_WORD = wordsD2[0];
string soFar(THE_WORD.size(), '*');
wordLength = THE_WORD.length();
}
// main loop
while ((incorrectGuesses < MAX_WRONG) && (soFar != THE_WORD))
{
cout << "\n- There are : "<< wordLength <<" letters in the word :\t" << soFar << endl;
cout << "\n- You have guessed " <<incorrectGuesses << " times wrong out of "<< MAX_WRONG << " allowed wrong guesses.\n";
cout << "\nLetters used : " << used << endl;
cout << "=====================================================";
char guess;
cout << "\n\t\tEnter a letter : ";
cin >> guess;
guess = toupper(guess); //make uppercase since secret word in uppercase
while (used.find(guess) != string::npos)
{
cout << "\nYou've already guessed the letter " << guess << endl;
cout << "Enter another letter / word: ";
cin >> guess;
guess = toupper(guess);
}
used += guess;
if (THE_WORD.find(guess) != string::npos)
{
cout << "=====================================================\n";
cout << "- Correct, The letter " << guess << " is in the word.\n";
// update soFar to include newly guessed letter
for (int i = 0; i < THE_WORD.length(); ++i)
if (THE_WORD[i] == guess)
soFar[i] = guess;
}
else
{
cout << "Sorry, " << guess << " isn't in the word.\n";
++incorrectGuesses;
pfnaDisplayMan[incorrectGuesses]();
}
}
// shut down
if (incorrectGuesses == MAX_WRONG)
cout << "\nYou've been hanged!";
else
cout << "\nYou guessed it!";
cout << "\nThe word was " << THE_WORD << endl;
return 0;
}
void DisplayMan0()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan1()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan2()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan3()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /X" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan4()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /X\\" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan5()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /X\\" << endl;
cout << "| /" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan6()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /X\\" << endl;
cout << "| / \\" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan7()
{
using namespace std;
cout << "\t\t_______" << endl;
cout << "\t\t|DONT" << endl;
cout << "\t\t|HANG" << endl;
cout << "\t\t|THE" << endl;
cout << "\t\t|MAN" << endl;
cout << "\t\t| O" << endl;
cout << "\t\t| _______ /XL" << endl;
cout << "\t\t__|_____| / \\" << endl;
}
Put incorrectGuesses out of those scopes. Because out of those scopes this variable is not declared.
if(dif == 1)
{
int incorrectGuesses = 0;
...
}
if(dif == 2)
{
int incorrectGuesses = 0;
...
}
if(dif == 3)
{
int incorrectGuesses = 0;
...
}
Should be
int incorrectGuesses = 0;
if(dif == 1)
{
...
}
if(dif == 2)
{
...
}
if(dif == 3)
{
...
}
Same issues for soFar, THE_WORD and wordLength. That part of code should be like this:
string THE_WORD;
string soFar;
int wordLength;
string used;
// cout ... cin ....
int incorrectGuesses = 0;
if(dif == 1)
{
random_shuffle(words.begin(), words.end());
THE_WORD = words[0]; // word to guess
wordLength = THE_WORD.length();
}
if(dif == 2)
{
random_shuffle(wordsD1.begin(), wordsD1.end());
THE_WORD = wordsD1[0];
wordLength = THE_WORD.length();
}
if(dif == 3)
{
random_shuffle(wordsD2.begin(), wordsD2.end());
THE_WORD = wordsD2[0];
wordLength = THE_WORD.length();
}
soFar.assign(THE_WORD.size(), '*');
M M. is correct. Your redeclaring the variables.
Just a small remark. I would use a Switch Case instead of a set of if statements. Changing:
if(dif==1){}
if(dif==2){}
if(dif==3){}
into
switch(dif){
case(1):
break;
case(2):
break;
case(3):
break;
}
Not for necessarily for readability but more to indicate that the value of dif isn't edited depending upon its value. For example:
Option 1:
dif = 1;
if(dif==1){ dif = 3; }
if(dif==2){}
if(dif==3){ dif = 7; }
Versus:
Option 2
dif = 1;
switch(dif){
case(1):
dif = 3;
break;
case(2):
break;
case(3):
dif = 7;
break;
}
Option 1 output: 7
Option 2 output: 3
You declare incorrectGuesses out of scope. It is NEVER declared or assigned a value. Declare it at the beginning of your function and assign it value in the other scopes.