Program returning garbage values when returning cstring - c++

My program is returning garbage values for variables modeled as c-strings. The program uses a class to model datatype Song. It appears the error would occur when the variable is set.
Inputs to the program and the outputs are listed below.
My apologies for the length of the code.
Why the random values?
Code
#include <iostream>
#include <cstring>
using namespace std;
const int MAX_CHAR = 100;
class Song
{
public:
//Default constructor
Song();
//Constructor
Song(char title[], char artist[], char album[], int min, int sec);
//Destructor
~Song();
//Accessor functions
char getTitle()const;
char getArtist() const;
char getAlbum() const;
int getMin() const;
int getSec() const;
//Mutator functions
void setTitle(const char*);
void setArtist(const char*);
void setAlbum(const char*);
void setMin(int);
void setSec(int);
private:
//Member Variables
char title[MAX_CHAR];
char artist[MAX_CHAR];
char album[MAX_CHAR];
int min;
int sec;
};
Song::Song(){}
Song::Song(char newTitle[],char newArtist[],char newAlbum[], int newMin, int newSec)
{
strncpy(title, newTitle, 100);
strncpy(artist, newArtist, 100);
strncpy (album, newAlbum, 100);
min = newMin;
sec = newSec;
}
Song::~Song(){}
//getter functions
char Song::getTitle() const
{
return title[MAX_CHAR];
}
char Song::getArtist() const
{
return artist[MAX_CHAR];
}
char Song::getAlbum() const
{
return album[MAX_CHAR];
}
int Song::getMin() const
{
return min;
}
int Song::getSec() const
{
return sec;
}
//setter functions
void Song::setTitle(const char newTitle[])
{
strcpy(title, newTitle);
}
void Song::setArtist(const char newArtist[])
{
strcpy(artist, newArtist);
}
void Song::setAlbum(const char newAlbum[])
{
strcpy(album, newAlbum);
}
void Song::setMin(int min)
{
this->min = min;
}
void Song::setSec(int sec)
{
this->sec = sec;
}
int main ()
{
char newTitle[MAX_CHAR];
char newArtist[MAX_CHAR];
char newAlbum[MAX_CHAR];
int min;
int sec;
cout << "Enter title: ";
cin >> newTitle;
cout << "Enter artist: ";
cin >> newArtist;
cout << "Enter album: ";
cin >> newAlbum;
cout << "Enter minutes: ";
cin >> min;
cout << "Enter seconds: ";
cin >> sec;
Song song;
song.setTitle(newTitle);
song.setArtist(newArtist);
song.setAlbum(newAlbum);
song.setMin(min);
song.setSec(sec);
cout << endl << "Title: " << song.getTitle() << endl <<
"Artist: " << song.getArtist() << endl <<
"Album: " << song.getAlbum() << endl <<
"Minutes: " << song.getMin() << endl <<
"Seconds: " << song.getSec() << endl;
return 0;
}
I/O
The inputs and the erroneous values that are consistently returned:
//Inputs
Enter title: title
Enter artist: artist
Enter album: album
Enter minutes: 3
Enter seconds: 20
//Outputs
Title: a
Artist: a
Album:
Minutes: 3
Seconds: 20

The problem is in your getter member functions where you actually return a character and not the array. You need to do the following changes:
const char* getTitle() const;
const char* getArtist() const;
const char* getAlbum() const;
const char* Song::getTitle() const {
return title;
}
const char* Song::getArtist() const {
return artist;
}
const char* Song::getAlbum() const {
return album;
}

Related

My char array in my c++ program will not print anything

I am doing my first C++ program for my class. I am really new to this program so I have a lot to learn. In my program I am suppose to create a Student class with Undergrad/grad/gradassist derived classes. The name and SSN fields have to be in a char array (I know string makes more sense but the teacher demands a char array). The program mostly works fine except it does not print anything in my char arrays. Please help!
#include <iostream>;
using namespace std;
class Student {
protected:
char name[21];
char ssn[10];
float gpa;
int credits;
public:
Student::Student() {};
Student(const char n[], const char ss[], float& gp, int& cred) {
name[21] = n[21];
ssn[10] = ss[10];
gpa = gp;
credits = cred;
}
virtual void print() {
cout << "Name: " << name << endl;
cout << "SSN: " << ssn << endl;
cout << "GPA: " << gpa << endl;
cout << "Credits: " << credits << endl;
}
virtual float tuition() const = 0;
};
class undergrad : public Student {
protected:
float undergrad_rate;
char* year;
public:
undergrad::undergrad() {}
undergrad(float ugr, char* yr, const char n[], const char ss[], float&
gp, int& cred) :
Student(n, ss, gp, cred), undergrad_rate(ugr), year(yr){}
void set_year(char* yr) {
year = yr;
}
char* getYear() {
return year;
}
float getRate() {
return undergrad_rate;
}
void print() {
Student::print();
cout << "Undergrad rate: " << undergrad_rate << endl;
cout << "year: " << year << endl;
}
float tuition() {
//cout << "The tuition is $35000" << endl;
return 35000;
}
};
class grad : public Student {
protected:
float grad_rate;
char* thesis;
public:
};
int main(){
char* jr = "Junior";
char* sr1 = "Senior";
char* fr = "Freshman";
char* sr = "Sophmore";
undergrad g(380, jr, "M", "000111222", 4.0, 12);
g.print();
system("pause");
return 0;
}
The problem lies here, in the way you initialize the members name and ssn:
Student(const char n[], const char ss[], float& gp, int& cred) {
name[21] = n[21];
ssn[10] = ss[10];
There's more than one thing wrong here
name and ssn are char arrays of size 21 and size 10 respectively. This means that valid indices range from 0 to 20 and 0 to 9 respectively. So by accessing name[21] and ssn[10] you're accessing elements past the end of the allotted memory.
Even if the indices were valid, you would just be assigning a single character by doing it this way.
In order to initialize these member variables the way you're intending, do this:
Student(const char n[], const char ss[], float& gp, int& cred) {
strcpy_s(name, sizeof(name), n);
strcpy_s(ssn, sizeof(ssn), ss);
This will copy all the characters comprising the input strings into your member variables and you will get the desired output.

C++ Operator Overloading always false

So I was able to fix it, however, the operator doesn't seem to be comparing them both since I always get false. There seems to be an error with the pLoan where it is not comparing both of them.
My code is
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
//Vehicle Class
class Vehicle {
public:
Vehicle();
void setPrice(double a);
void setMpg(int a);
double getPrice() const;
int getMpg() const;
void printVehicle() const;
Vehicle(double price, int mpg);
private:
double price;
int mpg;
};
//Loan Class
class Loan {
public:
void setBank(string a);
void setLoan(double a);
string getBank() const;
double getLoan() const;
void printLoan() const;
Loan(string bank = "", double loan = 0);
private:
string bank;
double loan;
};
//Car Class
class Car : public Vehicle {
public:
Car(double price = 0, int mpg = 0, string bank = "", double loan = 0, string name = "", int element = 0);
void setName(string a);
void setLoan(string b, double l, int element);
string getName() const;
void printFull() const;
void setNbrOfLoans(int a);
int getNbrOfLoans() const;
Loan* getpLoan() const;
~Car();
private:
string name;
Loan* pLoan;
int nbrOfLoans;
};
bool operator==(const Car &car1, const Car &car2) {
Loan* pLoan1 = car1.getpLoan();
Loan* pLoan2 = car2.getpLoan();
return ((car1.getPrice() == car2.getPrice()) && (car1.getMpg() == car2.getMpg()) && (car1.getName() == car2.getName())
&& (car1.getNbrOfLoans() == car2.getNbrOfLoans()) &&
(pLoan1[0].getBank() == pLoan2[0].getBank()) && (pLoan1[0].getLoan() == pLoan2[0].getLoan()));
}
//Main
int main() {
Car car1(24800, 22, "Citi", 21600, "Mustang", 1);
Car* pCar1 = &car1;
pCar1->setLoan("Citi", 21600, 0);
pCar1->printFull();
pCar1->setNbrOfLoans(1);
Car car2;
Car* pCar2 = &car2;
cout << boolalpha;
cout << "Enter the price of the car: ";
double price;
cin >> price;
pCar2->setPrice(price);
cout << "Enter the mpg: ";
int mpg;
cin >> mpg;
pCar2->setMpg(mpg);
cout << "Enter the name of the car: ";
string name;
cin >> name;
pCar2->setName(name);
string bank;
double loan;
int index;
cout << "Enter the amount of loans you obtained: ";
cin >> index;
pCar2->setNbrOfLoans(index);
for (int i = 0; i < index; i++)
{
cout << "Enter the name of bank " << i + 1 << ": ";
cin >> bank;
cout << "Enter the amount of loan " << i + 1 << ": ";
cin >> loan;
pCar2->setLoan(bank, loan, i);
}
if (pCar1 == pCar2)
cout << "Cars are the same. ";
else
cout << "Cars are not the same. ";
cout << endl;
pCar2->printFull();
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////
//Vehicle class function definitions
////////////////////////////////////////////////////////////////////////////////////////
Vehicle::Vehicle() {
price = 0;
mpg = 0;
}
Vehicle::Vehicle(double price, int mpg) {
price = price;
mpg = mpg;
}
void Vehicle::setPrice(double a) {
price = a;
}
void Vehicle::setMpg(int a) {
mpg = a;
}
double Vehicle::getPrice() const {
return price;
}
int Vehicle::getMpg() const {
return mpg;
}
void Vehicle::printVehicle() const {
cout << "Price: " << price << endl;
cout << "MPG: " << mpg << endl;
}
////////////////////////////////////////////////////////////////////////////////////////
//Loan Class function definitions
///////////////////////////////////////////////////////////////////////////////////////
Loan::Loan(string bank, double loan) {
Loan::bank = bank;
Loan::loan = loan;
}
void Loan::setBank(string a) {
bank = a;
}
void Loan::setLoan(double a) {
loan = a;
}
string Loan::getBank() const {
return bank;
}
double Loan::getLoan() const {
return loan;
}
void Loan::printLoan() const {
cout << "Bank: " << bank << endl;
cout << "Loan: " << loan << endl;
}
////////////////////////////////////////////////////////////////////////////////////
//Car Class function definitions
////////////////////////////////////////////////////////////////////////////////////
Car::Car(double price, int mpg, string bank, double loan, string name, int element) : Vehicle(price, mpg)
{
nbrOfLoans = element;
Car::name = name;
setMpg(mpg);
setPrice(price);
pLoan = new Loan[nbrOfLoans];
}
Loan* Car::getpLoan() const{
return pLoan;
}
void Car::setName(string a) {
name = a;
}
void Car::setLoan(string b, double l, int element) {
pLoan[element].setBank(b);
pLoan[element].setLoan(l);
}
string Car::getName() const {
return name;
}
int Car::getNbrOfLoans() const {
return nbrOfLoans;
}
void Car::setNbrOfLoans(int a) {
nbrOfLoans = a;
if (pLoan != NULL)
delete[] pLoan;
pLoan = new Loan[nbrOfLoans];
}
void Car::printFull() const {
cout << endl << "Car name: " << name << endl;
cout << "Price: " << getPrice() << endl;
cout << "MPG: " << getMpg() << endl;
for (int i = 0; i < nbrOfLoans; i++)
{
cout << "Loan #" << i + 1 << "." << endl;
cout << "Bank: " << pLoan[i].getBank();
cout << endl;
cout << "Loan amount: " << pLoan[i].getLoan();
cout << endl;
}
}
Car::~Car() {
delete[] pLoan;
}
Output:
IS always cars are not the same even when they are
Your main code is not calling your operator ==:
if (pCar1 == pCar2)
cout << "Cars are the same. ";
else
cout << "Cars are not the same. ";
here you're comparing the two pointers. To compare the two pointed-to objects you need
if (*pCar1 == *pCar2) ...
One more error:
pCar1->setLoan("Citi", 21600, 0);
pCar1->printFull();
pCar1->setNbrOfLoans(1);
setNbrOfLoans must be located before setLoan:
pCar1->setNbrOfLoans(1);
pCar1->setLoan("Citi", 21600, 0);
pCar1->printFull();

My output is not correct when displayed

My output name is not being displayed in my program. I have been looking at the code and
I just can't find my error
input
name : John Dough
id : 123445
start date : 10312014
shift: 2
output
name : ^^^^^^ <<<< I am having problem my name not being displayed
id : 123445
start date : 10312014
shift : 2
code
//This program demostrates a class and a derived class with constructors.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee
{
private:
char EmpName;
int EmpNum;
int HireDate;
public:
void setEmpName(char);
void setEmpNum(int);
void setHireDate(int);
char getEmpName() const;
int getEmpNum() const;
int getHireDate() const;
Employee();
};
void Employee::setEmpName(char x)
{
EmpName = x;
}
void Employee::setEmpNum(int y)
{
EmpNum = y;
}
void Employee::setHireDate(int z)
{
HireDate = z;
}
char Employee::getEmpName() const
{
return EmpName;
}
int Employee::getEmpNum() const
{
return EmpNum;
}
int Employee::getHireDate() const
{
return HireDate;
}
Employee::Employee()
{
cout << "I will ask you some questions about an employee.\n\n";
}
class ProductionWorker : public Employee
{
private:
int Shift;
double HourlyPayRate;
public:
void setShift(int);
void setHourlyPayRate(double);
int getShift() const;
double getHourlyPayRate() const;
ProductionWorker();
};
void ProductionWorker::setShift(int a)
{
Shift = a;
}
void ProductionWorker::setHourlyPayRate(double b)
{
HourlyPayRate = b;
}
int ProductionWorker::getShift() const
{
return Shift;
}
double ProductionWorker::getHourlyPayRate() const
{
return HourlyPayRate;
}
ProductionWorker::ProductionWorker()
{
cout << "After answering the questions,\n";
cout << "I will display the employee's information.\n\n\n";
}
int main()
{
ProductionWorker info;
char name[100];
int num;
int date;
int shift;
double rate;
cout << "What is the employee's name? ";
cin.getline(name, 100);
cout << "What is the employee's number? ";
cin >> num;
cout << "What is the employee's hire date?\n";
cout << "(Month, day, and year without any slashes,\n";
cout << "dashes, commas, or other punctuation.)\n";
cout << "For example, January 14, 1983 would look like 01141983. ";
cin >> date;
cout << "Does the employee work shift 1 or shift 2? ";
cin >> shift;
cout << "How much does the employee make per hour? ";
cin >> rate;
info.setEmpName(name[100]);
info.setEmpNum(num);
info.setHireDate(date);
info.setShift(shift);
info.setHourlyPayRate(rate);
cout << "\n\nHere is the employee's data:\n\n";
cout << "Employee's Name: " << info.getEmpName() << endl;
cout << "Employee's Number: " << info.getEmpNum() << endl;
cout << "Employee's Hire Date: " << info.getHireDate() << endl;
cout << "Employee's Shift: " << info.getShift() << endl;
cout << setprecision(2) << fixed;
cout << "Employee's Hourly Pay Rate: $" << info.getHourlyPayRate() << endl << endl;
return 0;
}
This is wrong: you're accessing an out-of-range character instead of passing the array to the function
char name[100];
//.. initialize name..
info.setEmpName(name[100]); // Accesses the 100th character (out-of-range [0-99])
void Employee::setEmpName(char x)
{
EmpName = x;
}
I would go for using std::string by changing EmpName (also wrong, it's not a single character) to a std::string
class Employee
{
private:
string EmpName;
int EmpNum;
int HireDate;
public:
void setEmpName(std::string& name);
void setEmpNum(int);
void setHireDate(int);
string getEmpName() const;
int getEmpNum() const;
int getHireDate() const;
Employee();
};
Also don't forget to change char name[100] to a std::string in the main function.
Live Example
You can of course accomplish this also with char arrays, in that case if you intend to use a fixed-size array you could either pass it by reference or just copy the content of a pointer to the array into a memory array for Employee.
There are multiple problems with your code.
First, the data type of Employee::EmpName should not be char. It should be a char array or even better would be a std::string.
Second the parameter of the setEmpName function should be either a const char* or a const std::string&.
Third, the name variable should perhaps be a std::string instead of a char array. Of course if you make that change the parameter of the setEmpName function should be const std::string&.
Fourth, when calling the setEmpName function you should just call it as follows: info.setEmpName(name).
Next, you should use std::getline(cin, name) instead of cin.getline(name, 100).
I'm first correcting your mistakes and then giving you a better alternative solution.
The member of your class and the setter function's parameter are only a single char. Change them to arrays:
char EmpName[100];
and
void setEmpName(char[]);
and in the implementation, you need to copy the content of the given array to your member:
void Employee::setEmpName(char[] x) {
memcpy(EmpName, x, 100);
}
However, this is the C way to do this.
The C++ way to do this is to use std::string. For this, change the types of the member, the parameters in the setter and in the getter as well as the type in main to std::string. To read a std::string, use the free-standing overload of getline which only takes the stream and the string (but no count):
getline(cin, name);

What is this error LNK2019 and 1120 [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 9 years ago.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//In this section I create the class HotelRoom
class HotelRoom
{
protected:
HotelRoom(){}
char room_Number[4];
char* guestName;
double rate;
public:
HotelRoom(char Num[], double daily, char* name);
HotelRoom(const HotelRoom &);
~HotelRoom();
int Get_Capacity();
int Get_Status();
double Get_Rate();
const char* Get_Number();
const char* Get_Guest();
int Change_Status(int Stat);
};
HotelRoom::HotelRoom(char Num[], double daily, char* name)
{
strcpy_s(room_Number, 4, Num);
guestName = new char[strlen(name) + 1];
strcpy_s(guestName, 20, name);
rate = daily;
}
HotelRoom::HotelRoom(const HotelRoom& room_r)
{
strcpy_s(room_Number, room_r.room_Number);
guestName = new char[strlen(room_r.guestName) + 1];
strcpy_s(guestName, 20, room_r.guestName);
rate = room_r.rate;
}
HotelRoom::~HotelRoom()
{
cout << endl << endl;
cout << "Decunstructor Activated." << endl;
delete[] guestName;
}
double HotelRoom::Get_Rate()
{
return rate;
}
const char* HotelRoom::Get_Number()
{
return room_Number;
}
const char* HotelRoom::Get_Guest()
{
return guestName;
}
class DerivedGuestRoom : public HotelRoom
{
public:
DerivedGuestRoom(int max, int stat, int nights);
DerivedGuestRoom(const DerivedGuestRoom&);
~DerivedGuestRoom();
protected:
int capacity;
int status = 0; //0 if unoccupied
int days;
};
DerivedGuestRoom::DerivedGuestRoom(int max, int stat, int nights) : capacity(max), status(stat), days(nights)
{
cout << "data members set";
}
DerivedGuestRoom::~DerivedGuestRoom()
{
cout << "\ndecunstrucor";
}
class DerivedMeetingRoom : public HotelRoom
{
public:
DerivedMeetingRoom(int seat, int stat);
DerivedMeetingRoom(const DerivedMeetingRoom&);
~DerivedMeetingRoom();
protected:
int seats;
int status; //1 if booked for meeting 0 otherwise
};
DerivedMeetingRoom::DerivedMeetingRoom(int seat, int stat) : seats(seat), status(stat)
{
cout << "data members set";
}
DerivedMeetingRoom::~DerivedMeetingRoom()
{
cout << "\ndecunstrucor";
}
void Display_info(HotelRoom&);
HotelRoom* Create_Hotel();
int main()
{
cout << setprecision(2)
<< setiosflags(ios::fixed)
<< setiosflags(ios::showpoint);
HotelRoom* Hotel_Rooms[200];
int count = 0;
char response;
cout << endl;
cout << "Do you want to enter information about a hotel room?(Y/N): ";
response = cin.get();
cin.get();
while (toupper(response) == 'Y' && count < 10)
{
Hotel_Rooms[count] = Create_Hotel();
++count;
cout << endl;
cout << "Do you want to enter information about a hotel room?(Y/N): ";
response = cin.get();
cin.get();
}
//Display the accounts created
for (int i = 0; i < count; ++i)
Display_info(*Hotel_Rooms[i]);
for (int i = 0; i < count; ++i)
delete Hotel_Rooms[i];
cout << endl;
system("PAUSE");
return 0;
}
void Display_info(HotelRoom& room)
{
cout << "\n\nGuest's Name: " << room.Get_Guest() << endl << endl;
cout << "\nYour room number is " << room.Get_Number() << endl << endl;
cout << "\nDaily rate is: " << room.Get_Rate() << endl << endl;
cout << endl;
cout << endl;
}
HotelRoom* Create_Hotel()
{
//These are the variables that will be holding data then passed through objects
char roomNumber[4];
char guestName[20];
double dailyRate = 89.00;
HotelRoom* room_ptr;
//This portion asks for user input
cout << "\nEnter Guest information\n\n";
cout << "Enter the room number: ";
cin.getline(roomNumber, 4);
cout << "Enter the guest's name: ";
cin.getline(guestName, 20);
cout << endl;
cin.get(); //Clears input buffer
room_ptr = new HotelRoom(roomNumber, dailyRate, guestName);
return room_ptr;
}
I took out HotelRoom(); from parent class constructor and I removed from the child class constructors. I Now only have this error:
LearningOOP.exe has triggered a breakpoint.
Which I have never encountered this so not sure what it means.
You declared a default constructor:
class HotelRoom
{
public:
HotelRoom();
}
and there is no implementation for that default constructor method. You can change to:
class HotelRoom
{
public:
HotelRoom() {}
}
or implement HotelRoom:HotelRoom { } in your cpp file.
You haven't defined your default constructor for the HotelRoom class.
class HotelRoom
{
protected:
char room_Number[4];
char* guestName;
double rate;
public:
HotelRoom(); //< Not defined!
HotelRoom(char Num[], double daily, char* name);
HotelRoom(const HotelRoom &);
~HotelRoom();
int Get_Capacity();
int Get_Status();
double Get_Rate();
const char* Get_Number();
const char* Get_Guest();
int Change_Status(int Stat);
};
An "Unresolved external symbol" linker error means that you've declared and used a piece of code in your application, but you haven't defined it before using it.
EDIT (Based on your follow up comment below):
You can't take the constructor out because it's needed in other parts of your code. See this line in your code:
DerivedGuestRoom::DerivedGuestRoom(int max, int stat, int nights) : HotelRoom(), capacity(max), status(stat), days(nights)
// ^---------^
// |
// Using the default constructor.
DerivedMeetingRoom::DerivedMeetingRoom(int seat, int stat) : HotelRoom(), seats(seat), status(stat)
// ^---------^
// |
// And again here!
You either need to remove implement the default constructor for the HotelRoom class, or add parameters to your DerivedMeetingRoom and DerivedGuestRoom class constructors so that you can use the HotelRoom(char Num[], double daily, char* name) constructor.

C++ I/O stream text file to array issue

My code is supposed to read 16 lines from a text file, and passing them into an array of 4 Objects, each with 4 attributes. The problem im encountering is that while everything seems to work fine on passing the text details to the array, the 1st array element of the last object in the array is not the one supposed to be! I am really stuck!
My code is :
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int CDsize;
class CD {
public:
// constructors
CD();
CD(string arist, string title, int year, double price);
// getter methods
string getArtist() const { return this->artist; }
string getTitle() const { return this->title; }
int getYear() const { return this->year; }
double getPrice() const { return this->price; }
// setter methods - inline functions
void setArtist(const string artist) { this->artist = artist; }
void setTitle(const string title) { this->title = title; }
void setYear(const int year) { this->year = year; }
void setPrice(const double price) { this->price = price; }
// option methods
private:
string artist;
string title;
int year;
double price;
};
/*Text menu option 1/*
void printallcds(CD MAX_CDS[])
{
int d;
for (d=0; d<=CDsize; d++)
{
cout << "CD Number : " << d << "/ Artist : " << MAX_CDS[d].getArtist() << "/
Title : " << cout << MAX_CDS[d].getTitle() << "/ Year of Release : " <<
MAX_CDS[d].getYear() << "/ Price : " <<
cout << MAX_CDS[d].getPrice() << endl;
}
}*/
int main() {
CD MAX_CDS[3];
int CDsize = (sizeof(MAX_CDS) / sizeof(MAX_CDS[0]));
ifstream CDfile("mystock.txt");
string data;
int yeardata;
double pricedata;
int i;
for (i = 0; i < 4; i++) {
getline(CDfile, data);
MAX_CDS[i].setArtist(data);
getline(CDfile, data);
MAX_CDS[i].setTitle(data);
getline(CDfile, data);
stringstream yearstream(data);
yearstream >> yeardata;
MAX_CDS[i].setYear(yeardata);
getline(CDfile, data);
stringstream pricestream(data);
pricestream >> pricedata;
MAX_CDS[i].setPrice(pricedata);
}
CDfile.close();
// testing
cout << MAX_CDS[3].getArtist() << endl; // error !!!
cout << MAX_CDS[3].getTitle() << endl;
cout << MAX_CDS[3].getYear() << endl;
cout << MAX_CDS[3].getPrice() << endl;
return 0;
}
// constructors implementation
CD::CD() {}
CD::CD(string artist, string title, int year, double price) {
this->artist = artist;
this->title = title;
this->year = year;
this->price = price;
}
}
You only have space for 3 items in MAX_CDS (see CD MAX_CDS[3];), yet you're referencing the 4th item in your error.
MAX_CDS[3] // Actually represents the 4th item
Counting starts from 0 in C++.
So, to reference the 3rd item, in your case the last item, use MAX_CDS[2] or MAX_CDS[CDSize-1].
cout << MAX_CDS[CDSize-1].getArtist() << endl;
cout << MAX_CDS[CDSize-1].getTitle() << endl;
cout << MAX_CDS[CDSize-1].getYear() << endl;
cout << MAX_CDS[CDSize-1].getPrice() << endl;
Rereading your question, you probably want more items!
CD MAX_CDS[4]; // Now you have 4 items available: indexed 0, 1, 2, and 3