Microsoft C exception: std::bad_alloc at memory location 0x0017F5E0 - c++

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).

Related

strcpy is copying sth character onwards i string . How to resolve this error?

My complete code is at pastebin.
There is a train database , and user enters train number to book a ticket.The function updt_tick should copy the values of train's name,source and destination into passenger's reservation object.
But the problem is that 5th character onwards are only being copied.
Here is the function's code sample.Train database is entered by user.
void updt_tick()
{
fstream f;
f.open("train.dat",ios::in | ios::binary);
while(f.read((char*)&t,sizeof(t)))
{
if (tno==t.tno)
{
strcpy(bp,t.source);
strcpy(dest,t.dest);
strcpy(tname,t.tname);
amt=SeatNum*t.PerSeatFare;
break;
}
}
f.close();
}
The train class is ->
class train
{
public:
int tno;
char tname[100];
char source[100];
char dest[100];
int PerSeatFare;
public:
void getdetail();
void showdetail();
}t;
The reserv class is ->
`
class reserv
{
//Assume that cust select train according to his source and destination.
public:
int pnr;
int tno;
char tname[100];
char pnames[10][100];
int ages[10];
int SeatNum;
int i;
int d,m,y;
float amt;
char bp[100],dest[100];
void updt_tick()
{
fstream f;
f.open("train.dat",ios::in | ios::binary);
while(f.read((char*)&t,sizeof(t)))
{
if (tno==t.tno)
{
strcpy(bp,t.source);
strcpy(dest,t.dest);
strcpy(tname,t.tname);
amt=SeatNum*t.PerSeatFare;
break;
}
}
f.close();
}
public:
void getresdet()
{
cout<<"Enter the details as follows\n";
cout<<"Train no:";
cin>>tno;
cout<<"No of seats required:";
cin>>SeatNum;
cin.ignore();
for(i=0; i<SeatNum ; i++)
{
cout<<"Passenger name:";
gets(pnames[i]);
cout<<"Passenger age:";
cin>>ages[i];
cin.ignore();
}
cout<<"Date of travel:";
cin>>d>>m>>y;
cout<<"Details Accepted\n";
pnr=rand();
updt_tick();
}
void showresdet()
{
cout<<"Pnr no:"<<pnr;
cout<<"\nTrain no:"<<tno;
cout<<"\nTrain name:";
puts(tname);
cout<<"Boarding point:";
puts(bp);
cout<<"Destination pt:";
puts(dest);
cout<<"No of seats reserved:"<<SeatNum;
for(i=0; i<SeatNum; i++)
{
cout<<"Passenger name:";
puts(pnames[i]);
cout<<"Passenger age:"<<ages[i];
}
cout<<"\nDate of reservation:"<<d<<"-"<<m<<"-"<<y;
cout<<"\nYou must pay:"<<amt<<endl;
}
int getpnr()
{
return pnr;
}
};
Edit: There was nothing wrong with strcpy or any other code. I made
the foolish mistake of giving the file name as "train.dat" instead of
"trains.dat:.
Im not sure how did you manage to read 5 characters, because there is a problem is in your code. The file which you use to store train details is "trainS.dat", not "train.dat".

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.

my relation of aggregation, association and composition doesnt work in this C++ program?

Im trying to make aggregation between Passenger and Bus class, Composition between [wheel, door, engine] and Bus class, simple association of [car, bus] and Vehicle. Also Driver is associated with Car. But I dont know how to write it in C++ code. My program is correct syntactically but giving run-time errors. Please help me.
#include<iostream>
#include<string>
using namespace std;
class Vehicle
{};
class Bus
{
Door door;
Wheel wheel;
Engine engine;
Passenger P;
string busNo;
int SeatingCapacity, SeatsReservedSofar;
public:
int GetSeatingCapacity();
void SetSeatingCapacity(int bCap);
string GetBusNo();
void SetBusNo(string bNo);
void ReserveSeat(Passenger P);
void DisplayInfo();
};
class Passenger
{
string Name;
char Gender;
public:
void SetPassengerName(string name);
string GetPassengerName();
void SetGender(char gender);
char GetGender();
};
class Car
{};
class Driver
{
};
class Wheel
{
};
class Door
{
};
class Engine
{
};
////////////////////////////////////
//Definition of Functions
////////////////////////////////////
Bus::Bus()
{
cout<<"Creating a new bus..."<<endl;
}
void Bus::SetSeatingCapacity(int bCap)
{
if(bCap>20 && bCap<50)
SeatingCapacity=bCap;
}
void Bus::SetBusNo(string bNo)
{
int len=bNo.length();
if(len>2 && len<5)
busNo=bNo;
}
void Passenger::SetPassengerName(string pname)
{
int len=pname.length;
if(len>0 && len<40)
Name=pname;
}
void Passenger::SetGender(char pgender)
{
if(pgender=='m' || pgender=='f')
Gender=pgender;
}
void Bus::ReserveSeat(Passenger P)
{
int capacity = GetSeatingCapacity(), rem;
if(capacity != SeatsReservedSofar)
{
SeatsReservedSofar++;
cout<<endl<<"Seat reserved for passenger";
rem=capacity-SeatsReservedSofar;
cout<<endl<<"Remaining Capacity : "<<rem;
}
else
{
cout<<endl<<"Seat reservation failed. No space left. ";
}
}
int main()
{
Bus abus;
cout<<"Enter max capacity of bus for passengers : ";
int capacity;
cin>>capacity;
abus.SetSeatingCapacity(capacity);
cout<<endl<<"Enter the bus registration no : ";
string regno;
std::getline(std::cin,regno);
cin.ignore();
abus.SetBusNo(regno);
cout<<endl<<".....Bus is created successfully. "<<endl<<endl;
string pname;
Passenger passenger;
char gender;
cout<<"Enter the passenger name: ";
std::getline(std::cin, pname);
cin.ignore();
passenger.SetPassengerName(pname);
cout<<"Enter the passenger gender <m for male and f for female>";
cin>>gender;
passenger.SetGender(gender);
abus.ReserveSeat(passenger);
char quest;
for(quest='y'; quest == 'y'; )
{
cout<<endl<<endl<<"Do you want to add more passengers? (y/Y for yes and another character for no)? ";
char quest;
cin>>quest;
}
system("pause");
}
First of all I think that you program cannot compile, why?
You've placed Passanger, Door, Wheel and Engine in Bus class. At moment of Bus class compilation those types are unknown to the compiler - you need to define them before Bus to use them in the Bus definition,
There is no Bus constructor declared in the class definition, it is placed outside the class, it will not work like that, you need to add Bus() in the Bus class,
in Passenger::SetPassengerName you forgot to place braces after length,
you forgot to define GetSeatingCapacity() method,
If there is a reservation system maybe you can consider to use some kind of Seat class which will keep information about reservation, for example a Passanger pointer or something like that.
To keep information about multiple Passangers you may use something like std::vector< std::weak_ptr< Passanger> >
To have multiple Wheels - something like std::array< Wheel> - same for seats, std::array< Seat>

Not understanding the error message I'm getting

I doing a freind function program according to this book I have and I did a little of my own code to the program. I puzzle because I get this error message that the "room_num" is undeclared and intellisense identifier "room_num" is undefine. I need help in understanding why this is happen and how to fix it. Here is the code I have been working on for the passed three weeks.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
class HotelRoom
{
friend int Transfer( HotelRoom&, int);
private:
int room_num;
int transroom_num;
int room_cap;
int occup_stat;
double daily_rt;
public:
HotelRoom(int room, int roomcap, int occup, int transroom, double rate = 89.00);
~HotelRoom();
int Display_Number(); //Displays room number and add the method Display_Guest()
int Get_Capacity();
int Get_Status();
double Get_Rate();
int Change_Status(int);
double Change_Rate(double);
void Display_Guest();
};
HotelRoom::~HotelRoom()
{
cout << endl<<endl;
cout << "Guest in room "<<room_num << " has checked out." <<endl;
}
int HotelRoom::Display_Number()
{
return room_num;
}
int HotelRoom::Get_Capacity()
{
return room_cap;
}
int HotelRoom::Get_Status()
{
return occup_stat;
}
int HotelRoom::Change_Status(int occup)
{
occup_stat = occup;
if (occup > room_cap)
{
return -1;
}
else
return occup_stat;
}
double HotelRoom::Get_Rate()
{
return daily_rt;
}
double HotelRoom::Change_Rate(double rate)
{
daily_rt = rate;
return daily_rt;
}
int Transfer(HotelRoom& room_r1, int transroom)
{
//if guest transfers to different hotel room, room is vacant and transroom is now occupied
room_r1.room_num = room_r1.transroom_num;
return room_num;
}
int main()
{
cout<< setprecision(2)
<<setiosflags(ios::fixed)
<<setiosflags(ios::showpoint);
int room = 0;
int roomcap = 4;
int transroom;
int occup;
double rate = 89.00;
cout<<"\nEnter the room number: "<<endl;
cin>>room;
cout<<"\nEnter the amount of guest to occupy this room: "<<endl;
cin>>occup;
cout<<"\nThe guest has decided to transfer rooms"<<endl;
cout<<"\nEnter the room to transfer the guest to"<<endl;
cin>>transroom;
HotelRoom room1(room,roomcap, occup, transroom, rate ); //initialize the object
if (room1.Change_Status(occup) == -1)
{
cout<<"You have exceeded the room capacity"<<endl;
}
else
{
cout <<"\nThe room number is ";
room1.Display_Number();
cout<<"."<<endl;
cout<<"\nThe name of the primary guest is ";
room1.Display_Guest();
cout <<"."<<endl;
cout<<"\nThe number of guest in the room is "<<room1.Change_Status(occup)<<"." <<endl;
cout<<"\nThe daily rate for room "<<room<< " is "<<room1.Get_Rate()<<"."<<endl<<endl;
cout<<"\nYou have tranferred the guest from room"<<room1.Display_Number()<<"to" <<Transfer(room1,transroom)<<endl;
}
cout<<"\nRoom ";
room1.Display_Number();
cout<<" is vacant."<<endl;
system("PAUSE");
return 0;
}
The function Transfer is not a method of HotelRoom, still you are trying to access room_num in it as if it was. You need to specify which room_num of which HotelRoom instance you mean. Probably you meant return room_r1.room_num instead of return room_num.
Also in your Transfer function you never use the parameter transroom, instead you are using a transroom_num from room_r1. This is probably not what you want.
Finally you haven't implemented the constructor and DisplayRoom of HotelRoom. You should create a stubs, which do nothing or print warnings as long as you haven't implemented the methods properly, so you can at least compile and link the code.
Since you are a beginner I would just stick with member functions and class private variables until you get better at it.
As far as the error message, my guess is that inside the function you are using room_num does not have access to the private parts of the HotelRoom class. Notice I said guess, that's because you should copy and paste the text on the output window here so we can see what exactly is happening.
First, you have to identify that room_num is class member variable.
int Transfer(HotelRoom& room_r1, int transroom)
{
room_r1.room_num = room_r1.transroom_num;
//because room_num is not non class member variable, you have to write like below.
return room_r1.room_num;
//return room_num;
}
Secondly, you did not write definition HotelRoom::HotelRoom(int,int,int,int,double), HotelRoom::Display_Guest(void). So you have to write this constructor and function for avoiding error LNK2019.

create an array of class objects in 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