create an array of class objects in c++ - c++

Hi guys I want to make an array of class objects....so that I can keep on creating as many objects during runtime as and when required
I wrote the following code, but its giving me error:
class contact{
public:
string name;//ALL CLASS VARIABLES ARE PUBLIC
int phonenumber;
string address;
contact(){//Constructor
name= NULL;
phonenumber= NULL;
address= NULL;
}
void input_contact_name(string s){//function to take contact name
name=s;
}
void input_contact_number(int x){//function to take contact number
phonenumber=x;
}
void input_contact_address(string add){//function to take contact address
address=add;
}
}
int main(){
contact *d;
d= new contact[200];
string name,add;
int choice;//Variable for switch statement
int phno;
static int i=0;//i is declared as a static int variable
bool flag=false;
cout<<"\tWelcome to the phone Directory\n";//Welcome Message
cout<<"Select :\n1.Add New Contact\n2.Update Existing Contact\n3.Delete an Existing Entry\n4.Display All Contacts\n5.Search for a contact\n6.Exit PhoneBook\n\n\n";//Display all options
cin>>choice;//Input Choice from user
while(!flag){//While Loop Starts
switch(choice){//Switch Loop Starts
case 1:
cout<<"\nEnter The Name\n";
cin>>name;
d[i]->name=name;
cout<<"\nEnter the Phone Number\n";
cin>>phno;
d[i]->input_contact_number(phno);
cout<<"\nEnter the address\n";
cin>>add;
d[i]->input_contact_address(add);
i++;
flag=true;
}
}
return 0;
}
Please can some one out figure out the reason??
Thanks in advance

Many problems:
Missing semicolon on the closing brace of the class, as maverik noted
Use of string without using namespace std; or using std::string; (or #include <string> for that matter)
Ditto #2 for cin and cout (and <iostream>)
d[i]-> is wrong; d[i] is a contact&, not a contact*, so use . instead of ->
name= NULL; and address= NULL; are nonsensical -- string is not a pointer type, and already default-constructs to empty
phonenumber= NULL; is technically valid, but still 'wrong'
Also, good lord, use some whitespace in your code.
EDIT (in response to comment): Your constructor should look like:
contact() : phonenumber() { }

You forget the ;
class contact {
...
}; // <- ; is neccessary

Related

OOP problem related to default constructor having setter from cin and pointer to object doesn't return the name

I have 3 fields,one void method to return minimum price,constructor with 3 parameters and a getter for name.
a) First I need to create an instance for this constructor and to return the name and the minimum price which I did.
b) Secondly I need to create a default constructor(so no parameters) and a setter method to set the fields but from the keyboard.
c) In the end I need to do the same thing as at a) but by using a pointer.
My problem is:
I don't know how to make b) cuz the setter doesn't work and when I try to return the name of the pointer object from c) it doesn't show anyting
#include <iostream>
using namespace std;
class CTest{
private:
string name;
float price1;
float price2;
public:
CTest(string name,float price1,float price2){
this->name = name;
this->price1 = price1;
this->price2 = price2;
}
CTest(){};
void set_values(string name,float price1,float price2){
cin>>name;
cin>>price1;
cin>>price2;
}
string get_name(){
return name;
}
void minimum_price() {
if(this->price1 < this->price2)
cout<<"Min price is " <<this->price1;
else
cout<<"Min price is " <<this->price2;
}
};
int main(){
CTest P ("Phone",450.9f,500.9f);
cout<<P.get_name();
cout<<endl;
P.minimum_price();
CTest *A = new CTest("Something",4.5f,3.5f);
cout<<A->get_name();
cout<<endl;
A->minimum_price();
return 0;
}
So this is wrong
void set_values(string name,float price1,float price2){
cin>>name;
cin>>price1;
cin>>price2;
}
because the three parameters hide the names of the your class member variables. So the values from cin go to the parameters not to your class.
What you probably meant is this
void set_values(){
cin>>name;
cin>>price1;
cin>>price2;
}
Now the values from cin will go to your class.

C++ code compiles but doesn't run [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am currently writing a Texas Hold'em code in order to learn more about c++ and gain experience. But I recently ran into a problem in which I have no idea what to do.My code compiles just fine without errors but once I make it run and it arrive at a specific function it just stops working (as in I get an error from CodeBlock saying your program has stopped working). I have tried cutting out parts such as loops in the function to see which specific part is the problem but after a couple of days im still at a stop.
Here is the function and class that I believe is the problem:
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
public:
void set_name(string a){name=a;}
string print_name(){return name;}
void card_generator();
string set_cards(int c){return cards[c];}
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
int p=0,k;
while(p<6){
k=0;
final_card[0][k]=tempCards[p];
k++;
p++;
}
while(p<12){
k=0;
final_card[1][k]=tempCards[p];
k++;
p++;
}
while(p<17){
k=0;
table_cards[k]=tempCards[p];
k++;
p++;
}
}
Here is the full code in case I am wrong of the source of the problem:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <ctime>
using namespace std;
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
public:
void set_name(string a){name=a;}
string print_name(){return name;}
void card_generator();
string set_cards(int c){return cards[c];}
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
string Player::cards[53];
string Player::final_card[2][6];
string Player::table_cards[5];
int main () {
int choice1=0, i, max_i, tempV;
string username;
cout<< "Welcome to Texas Hold'Em!\n1-Play\n2-Quit\n";//menu
while((choice1!=1)&&(choice1!=2)){//Makes sure that user enters correct input```
cin>>choice1;
if ((choice1!=1)&&(choice1!=2)){
cout<<"Invalid Input!\nTry again!\n";
}
}
system ("cls");
if (choice1==2){//End Program
return 0;
}
cout<<"How many players?[2-6]"<<endl;
while((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){//Makes sure that user enters correct input
cin>>i;
if ((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){
cout<<"Invalid Input!\nTry again!\n";
}
}
Player player[i];//creating array of players
player[0].card_generator();
max_i = i;//max_i is nb of players
i--;//since arrays start at 0
system("cls");
player[0].set_final_card(i,max_i);
player[0].print_cards();
if (choice1==1) {//SET NAMES OF ALL PLAYERS
for(i=0; i<max_i; i++){
cout<< "Whats your name?\n";
cin>>username;
player[i].set_name(username);
cout<<"Your name is "<< player[i].print_name()<< " and you have "<< player[i].print_bank()<<"$\n";
tempV=i+1;//used bc arrays start at 0
if(tempV!=max_i){
cout<< "Give PC to player "<< i+2 <<endl;
}
_sleep(3000);
system("cls");
}
}
return 0;
}
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
int p=0,k;
while(p<6){
k=0;
final_card[0][k]=tempCards[p];
k++;
p++;
}
while(p<12){
k=0;
final_card[1][k]=tempCards[p];
k++;
p++;
}
while(p<17){
k=0;
table_cards[k]=tempCards[p];
k++;
p++;
}
}
void Player::card_generator(){
string card_value[13];
card_value[0]="1";
card_value[1]="2";
card_value[2]="3";
card_value[3]="4";
card_value[4]="5";
card_value[5]="6";
card_value[6]="7";
card_value[7]="8";
card_value[8]="9";
card_value[9]="10";
card_value[10]="J";
card_value[11]="Q";
card_value[12]="K";
string card_type[4];
card_type[0]="of hearts";
card_type[1]="of diamonds";
card_type[2]="of clubs";
card_type[3]="of spades";
string card[53];
int x=0;
fill_n(card,53,0);
for (int j=0;j<4;j++){
for (int q=0;q<13;q++){
card[x]=card_value[q]+" "+card_type[j];
cards[x]=card[x];
x++;
}
}
}
If you have any criticism about the code itself even if not directly linked to problem feel free to tell me as I'm doing this to learn :D. Thank you in advance!!
#include <iostream>
#include <string>
#include <stdlib.h>
#include <ctime>
Be consistent in what you do. Including <stdlib.h> and <ctime> looks strange. Either include <cstdlib> and <ctime>, or include <stdlib.h> and <time.h>.
using namespace std;
Don't do this. This using imports all names from the std namespace, which is several hundreds. Only import those names that you actually need, or, alternatively, write std::time instead of the unqualified time. This makes it perfectly clear that you are referring to the time from the standard library instead of one that you might have defined yourself.
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
The cards should not be represented as strings, but as a separate data type called Card, with properties like suit and rank and a to_string method.
public:
void set_name(string a){name=a;}
To make your program fast, pass a as const std::string & instead of a simple string. This will prevent some copying of data. You should give a better name to the parameter, e.g. void set_name(const std::string &name) { this.name = name; }.
string print_name(){return name;}
This method does not print anything, therefore it must not be called print_name.
void card_generator();
Methods usually are named with verbs, not with nouns. So generate_cards would be a better name. But what does generate mean here? (I'm not a native English speaker, but would draw_cards describe it accurately?)
string set_cards(int c){return cards[c];}
A method called set_* usually modifies something. This one doesn't. Why did you name it this way?
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
Give better names to the parameters. From reading only this declaration, I have no idea what i and max_i might mean.
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
string Player::cards[53];
string Player::final_card[2][6];
string Player::table_cards[5];
It looks strange that the cards are stored in the Player class, since no poker player should ever have insight to all 52 cards. And why 53? Is there a joker in your game? These three fields should be moved to a class Table. This allows you to have multiple independent tables, which is nice for a big tournament.
int main () {
int choice1=0, i, max_i, tempV;
string username;
cout<< "Welcome to Texas Hold'Em!\n1-Play\n2-Quit\n";//menu
while((choice1!=1)&&(choice1!=2)){//Makes sure that user enters correct input```
Before reading the choice1 variable, you must initialize it. Since you don't do it, you invoke undefined behavior and everything that the program does after that is unpredictable.
cin>>choice1;
if ((choice1!=1)&&(choice1!=2)){
cout<<"Invalid Input!\nTry again!\n";
}
}
system ("cls");
if (choice1==2){//End Program
return 0;
}
cout<<"How many players?[2-6]"<<endl;
while((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){//Makes sure that user enters correct input
Same here. The user hasn't yet entered anything, so how can you check it?
cin>>i;
Add error handling for every input by enclosing it in an if clause: if (std::cin >> i) {.
if ((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){
cout<<"Invalid Input!\nTry again!\n";
}
}
Player player[i];//creating array of players
Don't use arrays, use a std::vector instead. This allows you to easily extend the table to have 10 players. In the end, there should not be a single 6 in your program.
player[0].card_generator();
max_i = i;//max_i is nb of players
Why do you call this variable max_i, when the comment says that max_players would be a better name?
i--;//since arrays start at 0
system("cls");
player[0].set_final_card(i,max_i);
player[0].print_cards();
if (choice1==1) {//SET NAMES OF ALL PLAYERS
for(i=0; i<max_i; i++){
cout<< "Whats your name?\n";
cin>>username;
player[i].set_name(username);
cout<<"Your name is "<< player[i].print_name()<< " and you have "<< player[i].print_bank()<<"$\n";
tempV=i+1;//used bc arrays start at 0
if(tempV!=max_i){
What does the V in tempV mean?
cout<< "Give PC to player "<< i+2 <<endl;
}
_sleep(3000);
system("cls");
}
}
return 0;
}
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
This 17 is a magic number. It would be better to write it as 5 + 6 * 2, since that makes it much clearer.
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
The 53 is wrong here. I can only be wrong. When you select from 52 cards with equal probability, it must be % 52.
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
Captain Giraffe has answered this question in the comments. If any newbies like me face a similar problem look up what a debugger is, as errors like these are called run-time errors. Check this page for a simple explanation: http://www.cplusplus.com/forum/articles/28767/ .

String in struct in struct in C++

So I've to do another exercise. This time I need to define a struct and a 100-elements array, which will store information about the book (title, author, ID number, price) and a simple function which will print info about all of the books stored. I started with that code:
#include <iostream>
using namespace std;
int main()
{
struct name_surname {string name, surname;};
struct book {string title; name_surname author_name, author_surname; int ID; int price;};
return 0;
}
And, well, what now? How can I store this in an array?
You just create an array of type book or name_surname or whatever you want.
Example:
book arr[100];
arr[0].title = "The last robot";
arr[0].ID = 2753;
Tips:
It's good programming practice if your structs/classes begin with with capital letter, so it's easier to distinguish them and so it is easier to name the variable the same name just without the capital letter. Example.
struct Name_surname
{
string name, surname;
};
Name_surname name_surname[100];
name_surname[0].name = "MyName";
Another tip is that I'd really suggest you learn how to research, this question has been answered millions of times and answers are all over the internet.
Here is my suggestion :
struct book
{
string title;
string name_surname;
string author_name;
string author_surname;
int ID;
int price;
};
struct Database
{
book *array;
void printDatabase()
{
for(int i = 0 ; i < 100 ;i++)
cout<<array[i].title<<endl;
}
Database()
{
array = new string [100];
}
};
Your name structure seems a little confused but creating an array is simply a case of declaring a variable with [] appended to it giving the size.
For example:
struct full_name
{
std::string firstname;
std::string surname;
};
struct book
{
std::string title;
full_name author;
int ID;
int price;
};
int main()
{
// Declare an array using []
book books[100]; // 100 book objects
// access elements of the array using [n]
// where n = 0 - 99
books[0].ID = 1;
books[0].title = "Learn To Program In 21 years";
books[0].author.firstname = "Idont";
books[0].author.surname = "Getoutalot";
}
What do you think about that:
#include <iostream>
using namespace std;
struct book {string title; string name; int ID; int price;} tab[100];
void input(book[]);
void print(book[]);
int main()
{
input(tab);
print (tab);
return 0;
}
void input(book tab[])
{
for (int i=0;i<3;i++)
{
cout<<"\nBook number: "<<i+1<<endl;
cout<<"title: ";cin>>tab[i].title;
cout<<"name: ";cin>>tab[i].name;
cout<<"ID: ";cin>>tab[i].ID;
cout<<"price: ";cin>>tab[i].price;
}
}
void print (book tab[])
{
for (int i=0; i<3; i++)
{
cout<<"\nBook number: "<<i+1<<endl;
cout<<"title: "<<tab[i].title;
cout<<"\nname: "<<tab[i].name;
cout<<"\nID: "<<tab[i].ID;
cout<<"\nprice: \n"<<tab[i].price;
}
}
I've done this with help from some Yt video. It works, but, is there a way to do it better, or just leave it how it is? And I have a question: Why those function parameters? Can't I just say tab[] or something else?
Computer languages are based on general and recursive rules. Just try to experiment and extrapolate with the basic understanding to build seemingly complex stuff. Coming to what you are trying to achieve:
We know, an array can be declared for any data-type (primitive or derived, one might call them POD and ADT).
We know, struct can comprise of any number of elements of any data-types.
Now, we can see that it is just as natural to say MyStruct[] as it is to int[].
It is better to prefer std::array if using modern compiler.

I keep receiving -2 as my updated salary

I am doing the following with my program:
1) Write the class definition for a class named Employee with name and salary as employee objects. The class contains two member functions: the constructor and a function that allows a program to assign values to the data members.
2) Add two member functions to the Employee class. One member function should allow any program using an employee object to view the contents of the salary data member. The other member function should allow the program to view the contents of the employee name data member.
3) Add another member function to the Employeeclass. The member function should calculate an employee objects new salary, based on a raise percentage provided by the program using the object. Before calculating the raise, the member function should verify that the raise percentage is greater than or equal to zero. If the raise percentage is less than zero, the member function should display an error message.
4) Write a main function that will create an array of employee objects, assign values to the objects, display the names and current salaries for all objects, ask user for the raise percentage and then calculate and display new salaries for all objects.
However, I receive -2 as my new salary after I input the data from the keyboard. I figured another set of eyes could see what I can't and would highly appreciate if someone can lend a hand, or at least steer me in the right direction. Perhaps it is a logic error, or something wrong with my declarations. Thank you for your time.
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
class EMPLOYEE
{
public:
EMPLOYEE();//
EMPLOYEE(string name, int salary);//
public:
string name;//name to be input
int salary;//salary to be input
int percentage_raise;
int updated_salary;
public:
int enter_values();
int output_values();
int NEW_SALARY();
};
//default constructor
EMPLOYEE::EMPLOYEE()
{
name = "";
salary = 0;
}
//constructor with name/salary variables
EMPLOYEE::EMPLOYEE(string NAME, int SALARY)
{
name= NAME;
salary= SALARY;
}
//name and salary to be input...
int EMPLOYEE::enter_values()
{ cout<<"Enter name and salary: ";
cin>> name;
cin>>salary;
return 0;
}
//output
int EMPLOYEE::output_values()
{ cout<<"Name: "<<name<<endl;
cout<<"Salary: "<<salary<<endl;
return 0;
}
//
int EMPLOYEE::NEW_SALARY()
{
if ( percentage_raise >= 0)
{ int updated_salary;
int raise= (salary *percentage_raise)/100;
updated_salary += raise;
}
else if(percentage_raise< 0)
{ cout<<"Error Message"<<endl;
}
return 0;
}
int main()
{
EMPLOYEE employees[100];
EMPLOYEE percent_to_be_raised;
int i;
for(i =0 ;i<100 ; i++)
{ employees[i]=EMPLOYEE();
employees[i].enter_values();
employees[i].name;
employees[i].salary;
// employees[i].NEW_SALARY();
employees[i].output_values();
cout<<"How much should the salary be raised by?"<<endl;
cin>>percent_to_be_raised.percentage_raise;
cout<<"-----------------------------"<<endl;
cout<<employees[i].name <<"'s new salary is "<<percent_to_be_raised.updated_salary<<endl;
}
}
You need to rewrite this quite alot.
A few pointers:
EMPLOYEE percent_to_be_raised;
Is completely off base. The task states that this calculation should be done in an employee member function. I.e. the raise should be performed as
Employee alfred;
std::cin>> alfred.salary;
double raise;
std::cin>> raise;
alfred.raise_salary(raise); // this is what the task asks for.
Use a naming convention.
Employee
is fine for a c++ class with a capitalized class name convention. EMPLOYEE is not; this looks like a macro name.
Member function usually starts with non-capitalized
Employee::new_salary( the_salary );
Follow the examples you have available from the course material.
Of course
employees[i].name;
employees[i].salary;
Does not do anything. Please review your code in detail and start at the first spot you don't understand.
Note that the OP coding style convention is used to assist the OP. I am aware of the proper naming convention for classes, member functions, and class data members (e.g. see the answer by Captain Giraffe for more).
Inside of:
int EMPLOYEE::NEW_SALARY()
{
if ( percentage_raise >= 0)
{ int updated_salary;
int raise= (salary *percentage_raise)/100;
updated_salary += raise;
}
} // added this to close the function properly
there is a locally declared variable, which is typed identically to the public access data member of the same name. What is the intention here?
Most likely it should be coded like so:
int EMPLOYEE::NEW_SALARY()
{
if ( percentage_raise >= 0)
{
int raise = (salary *percentage_raise)/100;
updated_salary += raise;
}
} // added this to close the function properly
There are design considerations for having all class member data public, as well as having an integer for a percentage. From the calculation above, it looks like only values of one, two, three, etc. are allowed for the percentage number. What is the class supposed to do if a raise is 3.75 percent?
The constructor has to set ALL class data members to something meaningful too. For example, the percentage_raise and updated_salary variables are ignored. Most likely the default constructor has to be updated to:
//default constructor
EMPLOYEE::EMPLOYEE()
{
name = "";
salary = 0;
percentage_raise = 0;
updated_salary = 0;
}
The name and salary constructor has to be updated too. It should probably look like (using the style convention posted by the OP):
//constructor with name/salary variables
EMPLOYEE::EMPLOYEE(string NAME, int SALARY)
{
name = NAME;
salary = SALARY;
percentage_raise = 0;
updated_salary = salary;
}

Microsoft C exception: std::bad_alloc at memory location 0x0017F5E0

I am writing a hangman game. I am getting this error:Microsoft C++ exception: std::bad_alloc at memory location 0x0017F5E0. When I step through the program it stops here and the output window gives me this error: Microsoft C++ exception: std::bad_alloc at memory location 0x0017F5E0 and I see the message "error reading characters of string.
this is my code
void Player::boardSetup()
{
unsigned seed =time(0);
srand(seed);
word=rand()%100;
Words1[word]=Word1;
strcpy_s(Copy,Word1.c_str());
size=strlen(Word1.c_str());
for(index=0;index<size;index++)
{
Guess[index]='-';
cout<<Guess[index]<<endl;
}
}
Here is all my code. I hope this helps so you do not have to guess.
class Player
{ public:
string fName;
string lName;
int DOB;
string username;
int SS4;
string email;
int won;
int lost;
const int static WordSIZE=15;
int const static totalWORDS=100;
string static Letters[WordSIZE];
string static Words1[totalWORDS];
char static Copy[WordSIZE];
char static Guess[WordSIZE];
int index;
int word;
int size;
int isComing;//I need function to initialize these.
char letter;
bool correct;//I need a function to initialize these.
string Word1;
public:
Player(string,string,int,string,int,string);
void getWords();
void boardSetup();
void playGame();
void deathBed(int);
};
Player::Player(string first,string last,int birth, string nicname,int SS,string mail)
{
fName=first;
lName=last;
DOB=birth;
username=nicname;
SS4=SS;
email=mail;
isComing=0;
correct=true;
}
const int static WordSIZE=15;
int const static totalWORDS=100;
string Player:: Words1[totalWORDS];
char Player:: Copy[WordSIZE];
char Player:: Guess[WordSIZE];
string Player:: Letters[WordSIZE];
void Player::getWords()
{
ifstream WordBank;
int index=0;
WordBank.open("C:\\WordBank\\words.txt");
if(WordBank)
{
while(WordBank>>Words1[index])
{
index++;
}
WordBank.close();
}
else
{
cout<<"There was an error."<<endl;
}
}
/*string *words2;
words2=new string[100];
ifstream WordBank;
int index;
WordBank.open("C:\\WordBank\\words.txt");
if(WordBank)
{
for(index=0;(WordBank>>words2[index]);index++)
{
}
WordBank.close();
}
else
{
cout<<"There was an error."<<endl;
}
delete [] words2;
words2=0;
}*/
void Player::boardSetup()
{
unsigned seed =time(0);
srand(seed);
word=rand()%100;
Words1[word]=Word1;
strcpy_s(Copy,Word1.c_str());
size=strlen(Word1.c_str());
for(index=0;index<size;index++)
{
Guess[index]='-';
cout<<Guess[index]<<endl;
}
}
}
void Player::playGame()
{
while(isComing!=7)
{
deathBed(isComing);
cout<<Guess<<endl;
cout<< "Please guess a letter."<<endl;// or press 0 to go to the main screen for help
cin>>letter;
letter=toupper(letter);
for (index=0;index<size;index++)
{
if(Copy[index]==letter)
{
cout<<"Nice Job"<<endl; //add the ability to see the word
Guess[index]=letter;
cout<<Guess[index]<<endl;
}
else if(strcmp(Word1.c_str(),Guess)==0)
{
cout<<"You WIN!!!"<<endl;
return;
}
else if (correct=false)
{
cout<<"Please,Try again"<<endl;
isComing++;
}
}
}
void deathBed(int isComing);
cout<<"The word is"<<Words1[word]<<"."<<endl;
//draw a big red noose. call a function for it.
}
struct userInfo
{
string FName;
string LName;
int dob;
string Username;
int ss4;
string Email;
};
userInfo getUserInfo();
int main()
{
userInfo i;
i=getUserInfo();
Player player1(i.FName,i.LName,i.dob,i.Username,i.ss4,i.Email);
player1.getWords();
player1.boardSetup();
player1.playGame();
return 0;
}
userInfo getUserInfo()
{
userInfo info;
cout<<"What is your first name?"<<endl;
cin>> info.FName;
cout<<"What is your last name?"<<endl;
cin>>info.LName;
cout<<"What is your date of birth"<<endl;
cin>>info.dob;
cout<<"Please enter a user name."<<endl;
cin>>info.Username;
cout<<"Please enter the last four digits of your Social Security number."<<endl;
cin>>info.ss4;
cout<<"Please enter your email address."<<endl;
cin>>info.Email;
return info;
}
I'm not going to debug your program, but here are some issues that I found:
Use std::vector not arrays.
Arrays don't know their size, they can't expand on demand and messy when passing around.
Use your structures.
You create a userInfo structure only to fill from the input.
Your Player class has the same fields as userInfo. You should create a userInfo variable in Player.
Pass the whole userInfo structure to the Player constructor.
You could use an initialization list to copy the userInfo from the constructor parameter to the userInfo variable in Player.
Separate your concepts.
In your present design, the board is embedded into every Player.
In main(), at least one player must get the board words.
I suggest making a Board class. Each Player can give a guess to the Board and it can return a response and redraw itself.
The Board would be in charge of initializing its word list and choosing a guess.
Separate themes into separate translation units.
Put the Player into its own header and source file.
The main function should be in a separate source file.
This would allow you to make changes in main without recompiling the Player.
The concept also helps support loose coupling, encapsulation, and data hiding.
Let the objects do the work.
The userInfo class should have a method to obtain its member info from the outside world.
A Board class should perform work related to the board.
A Player class should perform work related to a player.
The main function should glue everything together (such as coordinating players).