int a[9],b[9],i;
for(i=0; num>0; i++)
{
a[i]=num%2;
num= num/2;
}
I am working on decimal to binary conversion. I can convert themi want answer in 8 bits. And it gives me as, for example x =5, so output will be 101, but i want 00000101. Is there any way to append zeros in the start of array, without using any library.
The health clinic manages patients and the patient manages their own data.
You can run/check this code in https://repl.it/#JomaCorpFX/StdGetLine#main.cpp
Code
#include <iostream>
#include <string>
#include <vector>
class Patient
{
private:
std::string phoneNumber;
std::string name;
std::string email;
float weight;
float height;
public:
void SetName(const std::string &name)
{
this->name = name;
}
void SetEmail(const std::string &email)
{
this->email = email;
}
void SetPhoneNumber(const std::string &phoneNumber)
{
this->phoneNumber = phoneNumber;
}
void SetWeight(const float &weight)
{
this->weight = weight;
}
void SetHeight(const float &height)
{
this->height = height;
}
std::string GetName()
{
return this->name;
}
std::string GetEmail()
{
return this->email;
}
std::string GetPhoneNumber()
{
return this->phoneNumber;
}
float GetWeight()
{
return this->weight;
}
float GetHeight()
{
return this->height;
}
public:
};
class HealtClinic
{
private:
std::vector<Patient> patients;
public:
void AddPatient()
{
Patient p;
std::cout << "\nEnter name : ";
std::string sdata;
std::getline(std::cin, sdata);
p.SetName(sdata);
std::cout << "\nEnter email : ";
std::getline(std::cin, sdata);
p.SetEmail(sdata);
std::cout << "Enter phone number : ";
std::getline(std::cin, sdata);
p.SetPhoneNumber(sdata);
int idata;
std::cout << "Enter weight in kg : ";
std::cin >> idata;
p.SetWeight(idata);
std::cout << "Enter height in meters: ";
std::cin >> idata;
p.SetHeight(idata);
patients.push_back(p);
}
void ShowPatients()
{
std::cout << "--- PATIENTS ---" << std::endl;
for (int i = 0; i < patients.size(); i++)
{
std::cout << "--- " << i << std::endl;
std::cout << "Name: " << patients[i].GetName() << std::endl;
std::cout << "Email: " << patients[i].GetEmail() << std::endl;
std::cout << "Phone number: " << patients[i].GetPhoneNumber() << std::endl;
std::cout << "Weight: " << patients[i].GetWeight() << std::endl;
std::cout << "Height: " << patients[i].GetHeight() << std::endl;
std::cout << std::endl;
}
}
};
int main()
{
HealtClinic clinic;
clinic.AddPatient();
clinic.ShowPatients();
return EXIT_SUCCESS;
}
Output
Enter name : Joma
Enter email : joma#email.com
Enter phone number : 123456789
Enter weight in kg : 88
Enter height in meters: 1.8
--- PATIENTS ---
--- 0
Name: Joma
Email: joma#email.com
Phone number: 123456789
Weight: 88
Height: 1
Related
I recently made an application with 1 superclass and 2 subclasses. The main idea of it is storing information in 3 different list. My question is, can you only use 1 list for all 3 classes? Even though the 2 subclasses have some extra members. Someone told me that you could use unique_ptr as a member of the superclass and make only 1 list. I have read about it on the internet, but I can't quite get it. Any suggestions? Thank you for your time.
class Student {
std::string Name;
std::string Pinfo;
std::map < std::string, float > Ngradelist;
public:
std::string getName() {return Name;}
std::string getPinfo() {return Pinfo;}
virtual void InsertGradeList(std::string a, float b) {
for(auto& it : Ngradelist)
Ngradelist.insert(std::pair <std::string, float > (a,b));
}
Student( std::string n, std::string p, std::map < std::string, float > Ng) :
Name(std::move(n)), Pinfo(std::move(p)), Ngradelist(std::move(Ng)) {}
virtual void Display() {
std::cout << "Name: " << Name << std::endl;
std::cout << "Personal information: " << Pinfo << std::endl;
std::cout << "NCourse:" << std::endl;
for(auto& it : Ngradelist)
std::cout << " " << it.first << " Grade: " << it.second << std::endl;
}
};
class HWStudent : public Student {
std::string FieldOfWork;
std::map<std::string, float> HWgradelist;
public:
void InsertGradeList(std::string a, float b) override{
for (auto &it : HWgradelist)
HWgradelist.insert(std::pair<std::string, float>(a, b));
}
HWStudent(std::string n, std::string p, std::map<std::string, float> Ng, std::string f,
std::map<std::string, float> HWg) : Student(std::move(n), std::move(p), std::move(Ng)),
FieldOfWork(std::move(f)), HWgradelist(std::move(HWg)) {}
void Display() override {
Student::Display();
std::cout << "Field of Work: " << FieldOfWork << std::endl;
std::cout << "HWCourse:" << std::endl;
for(const auto& it : HWgradelist)
std::cout << " " << it.first << " Grade: " << it.second << std::endl;
}
};
class SWStudent : public Student {
std::map<std::string, float> SWgradelist;
std::list < std::string > Languages;
public:
void InsertGradeList(std::string a, float b) override {
for (const auto &it : SWgradelist)
SWgradelist.insert(std::pair<std::string, float>(a, b));
}
SWStudent(std::string n, std::string p, std::map<std::string, float> Ng, std::list < std::string > l,
std::map<std::string, float> SWg) : Student(std::move(n), std::move(p), std::move(Ng)),
Languages(std::move(l)), SWgradelist(std::move(SWg)) {}
void Display() override {
Student::Display();
std::cout << "SWCourse:" << std::endl;
for(const auto& it : SWgradelist)
std::cout << " " << it.first << " Grade: " << it.second << std::endl;
std::cout << "SW Languages:" << std::endl;
for(const auto& it : Languages)
std::cout << " " << it << std::endl;
}
};
std::list < Student > listaStudenti;
std::list < HWStudent > HWlistaStudenti;
std::list < SWStudent > SWlistaStudenti;
void InsertListaStudenti(unsigned short option) {
unsigned short numbers;
std::string name , pinfo, course, fieldofwork, hwcourse, swcourse;
std::string language;
float grade = 0, hwgrade, swgrade;
std::list < std::string > languagelist;
if(option == 1) {
std::cout << "Insert name: ";
std::cin >> name;
std::cout << "Insert personal information: ";
std::cin >> pinfo;
std::cout << "Insert course: ";
std::cin >> course;
std::cout << "Insert grade: ";
std::cin >> grade;
Student student(name, pinfo, {{course, grade}});
listaStudenti.push_back(student);
}
if(option == 2) {
std::cout << "Insert name: ";
std::cin >> name;
std::cout << "Insert personal information: ";
std::cin >> pinfo;
std::cout << "Insert course: ";
std::cin >> course;
std::cout << "Insert grade: ";
std::cin >> grade;
std::cout << "Insert hwcourse: ";
std::cin >> hwcourse;
std::cout << "Insert hwgrade: ";
std::cin >> hwgrade;
std::cout << "Insert fieldofwork: ";
std::cin >> fieldofwork;
HWStudent hwstudent(name, pinfo, {{course, grade}}, fieldofwork,{{hwcourse, hwgrade}});
HWlistaStudenti.push_back(hwstudent);
}
if(option == 3) {
std::cout << "Insert name: ";
std::cin >> name;
std::cout << "Insert personal information: ";
std::cin >> pinfo;
std::cout << "Insert course: ";
std::cin >> course;
std::cout << "Insert grade: ";
std::cin >> grade;
std::cout << "Insert swcourse: ";
std::cin >> swcourse;
std::cout << "Insert swgrade: ";
std::cin >> swgrade;
std::cout << "How many languages: ";
std::cin >> numbers;
for(auto it = 0;it < numbers; ++it) {
std::cout << "Insert language: ";
std::cin >> language;
languagelist.push_back(language);
}
SWStudent swstudent(name, pinfo, {{course, grade}},languagelist,{{swcourse, swgrade}});
SWlistaStudenti.push_back(swstudent);
}
}
int main() {
unsigned short option = 10;
while(option != 0) {
std::cout << "1.Add student." << std::endl;
std::cout << "2.Add HW student." << std::endl;
std::cout << "3.Add SW student." << std::endl;
std::cout << "4.Display Student." << std::endl;
std::cout << "5.Display HW Student." << std::endl;
std::cout << "6.Display SW Student." << std::endl;
std::cout << "0 is for exit." << std::endl;
std::cout << "Option is : ";
std::cin >> option;
switch (option) {
case 0 : {
std::cout <<" You chose to leave.";
exit;
break;
}
case 1 : {
InsertListaStudenti(option);
break;
}
case 2 : {
InsertListaStudenti(option);
break;
}
case 3: {
InsertListaStudenti(option);
break;
}
case 4: {
for(auto &it : listaStudenti)
it.Display();
break;
}
case 5: {
for(auto &it : HWlistaStudenti)
it.Display();
break;
}
case 6: {
for(auto &it : SWlistaStudenti)
it.Display();
break;
}
}
}
}
You can indeed have
std::list<std::unique_ptr<Student>> students;
instead of
std::list<Student> listaStudenti;
std::list<HWStudent> HWlistaStudenti;
std::list<SWStudent> SWlistaStudenti;
with insertion similar to
Student student(name, pinfo, {{course, grade}});
students.push_back(std::make_unique<Student>(std::move(student)));
// or std::make_unique<Student>(name, pinfo, std::map<std::string, float>{{course, grade}})
HWStudent hwstudent(name, pinfo, {{course, grade}}, fieldofwork, {{hwcourse, hwgrade}});
students.push_back(std::make_unique<HWStudent>(std::move(hwstudent));
instead of
Student student(name, pinfo, {{course, grade}});
listaStudenti.push_back(student);
HWStudent hwstudent(name, pinfo, {{course, grade}}, fieldofwork,{{hwcourse, hwgrade}});
HWlistaStudenti.push_back(hwstudent);
Issue would be with your "filtering":
for (auto& student : SWlistaStudenti) {
student.Display();
}
becomes
for (auto& studentPtr : SWlistaStudenti) {
if (auto ptr = dynamic_cast<SWStudent*>(studentPtr.get())) ptr->Display();
}
but (to show only regular students (not HW/SW))
for(auto& student : listaStudenti) { student.Display(); }
becomes
for (auto& studentPtr : students) {
if (!dynamic_cast<SWStudent*>(studentPtr.get())
&& !dynamic_cast<HWStudent*>(studentPtr.get())) {
studentPtr->Display();
}
}
One list allows to treats them equality BTW:
To display all students:
for (auto& studentPtr : students) { studentPtr->Display(); }
instead of
for (auto& student : listaStudenti) { student.Display(); }
for (auto& student : HWlistaStudenti) { student.Display(); }
for (auto& student : SWlistaStudenti) { student.Display(); }
I am trying to add a customer to my vector and when I run my program the copy constructor is called. I am doing an assignment where I need a vector of customers and have to be able to add customers, display customers, find customers and load/store the data. Have I created the vector wrong? I am only new to c++ and really unsure about vectors.
Code from Main.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include "Customer.h"
using namespace std;
void OutputFileStream();
void parseLine(const string& str);
void InputFileStream();
void save(vector<Customer> customers);
void load(vector<Customer>& customers);
void addCustomer(vector<Customer>& vect);
void displayAll(vector<Customer>& customers);
//void printActions();
vector<Customer> customers;
void OutputFileStream()
{
cout << "Creating and writing to file: Customer.txt" << endl;
ofstream outStream("customers.txt"); // write mode (overwrites existing data)
if (outStream.good())
{
int customerID = 150033;
outStream << "This is a line of text.\n";
outStream << "This is another line of text.\n";
outStream << "This is a line of text.\n";
int numOfPurchases = 4;
int purchases = 0;
outStream << customerID << "Mr" << "Jack" << "New" << numOfPurchases << purchases << endl;
//int *purchases = customers[0].getPurchases();
outStream.close(); // close file
cout << "File written.\n" << endl;
}
else
cout << "Unable to open file";
}
void parseLine(const string& str) {
stringstream strStream(str); //create string stream from the string
// int customerID;
string title;
string name;
string type;
//int numOfPurchases;
//int purchases;
string s;
int customerID = 150033;
getline(strStream, s, ';');
customerID = stoi(s);
getline(strStream, title, ';');
getline(strStream, name, ';');
getline(strStream, type, ';');
int numOfPurchases = 4;
getline(strStream, s, ';');
numOfPurchases = stoi(s);
int purchases = 0;
getline(strStream, s, ';');
purchases = stoi(s);
int* purchasesArray = new int[3];
purchasesArray[0] = (purchases & (255 << 16)) >> 16;
purchasesArray[1] = (purchases & (255 << 8)) >> 8;
purchasesArray[2] = purchases & 255;
for (int i = 0; i < 3; i++)
{
cout << purchasesArray[i];
}
cout << " CustomerID: " << customerID << "Title:" << title << " Name: " << name << " Type:" << type << " Number of Purchases: " << numOfPurchases << "Purchases: " << purchases << endl;
}
void InputFileStream() {
cout << "Reading from a semi-colon delimited txt file" << endl;
string line;
ifstream inStream("customers.txt"); //opens file as an input file stream
if (inStream.good()) //if the file is opened successfully and not empty
{
while (getline(inStream, line)) //reads line until false return
{
parseLine(line);
}
inStream.close();
}
else
cout << "unable to open file or the file is empty!";
}
void save(vector<Customer> customers)
{
ofstream out("customers.txt");
if(out)
{
for (Customer& c : customers)
{
out << c.save();
}
out.flush();
out.close();
}
else
{
cout << "Error Writing to File" << endl;
}
}
void load(vector<Customer>& customers)
{
ifstream in("customers.txt");
if (in) {
string line;
while (!in.eof())
{
getline(in, line);
if (line != "")
{
Customer c;
c.parse(line);
customers.push_back(c);
}
}
}
}
void addCustomer(vector<Customer>& customers) {
Customer customer;
cin >> customer;
customers.push_back(customer);
}
void displayAll(vector<Customer>& customers)
{
cout << "\nvector contains:\n";
for (Customer c : customers)
cout << c.getCustomerID() << " " << c.getTitle() << c.getName() << c.getNumOfPurchases() << c.getPurchases() << c.getType() << endl;
cout << endl;; //same as calling customer
}
//
//int getCustomerByPurchaseNumber(int numOfPurchases) {
// vector<Customer> customers;
// int pos = -1;
// for (int i = 0; i < customers.size(); i++) {
// if (customers.at(i).getNumOfPurchases() == numOfPurchases) {
// return i;
// }
// }
// return pos;
//}
//
//void findCustomerByPurchaseNumber(vector<Customer>& customers) {
// vector<Customer> customers;
// int numOfPurchases;
// cout << "Please Enter Your Purchase Number:" << endl;
// cin >> numOfPurchases;
// int pos = customers.get(pos);
// getCustomerByPurchaseNumber(numOfPurchases);
// if (pos == -1) {
// cout << "Number of Purchase Not Found! " << endl;
// return customers;
// }
// else {
// cout << "Number Of Purchase Found! " << endl;
//
// return customers* = customers;
// }
//
//}
int main()
{
vector<Customer> customers;
Customer c1 = { 150031, "Mr", "John", 5, 333,362,341, "New" };
customers.push_back(c1);
//InputFileStream();
/* Customer customer;
customer.setCustomerID(150032);
customer.setTitle("Mr");
customer.setName("Joey");
customer.setNumOfPurchases(3);
customer.setPurchases(366, 352, 334);
customer.setType("New");
cout << customer.getCustomerID() << endl;
cout << customer.getTitle() << endl;
cout << customer.getName() << endl;
cout << customer.getNumOfPurchases() << endl;
cout << customer.getPurchases() << endl;
cout << customer.getType() << endl;
*/
return 0;
}
Code from Customer.cpp:
#include "Customer.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include<utility>
using namespace std;
//default constructor
Customer::Customer() {
}
//Full constructor
Customer::Customer(int customerID, string title, string name, int numOfPurchases, int purchase1, int purchase2, int purchase3, string type)
{
this->customerID = customerID;
this->title = title;
this->name = name;
this->numOfPurchases = numOfPurchases;
purchases = new int[3];
purchases[0] = purchase1;
purchases[1] = purchase2;
purchases[2] = purchase3;
this->type = type;
}
Customer::Customer(const Customer& source) //copy constructor
{
cout << "copy constructor called" << endl;
this->customerID = source.customerID;
this->title = source.title;
this->name = source.name;
this->numOfPurchases = source.numOfPurchases;
this->purchases = new int[3];
purchases[0] = source.purchases[0];
purchases[1] = source.purchases[1];
purchases[2] = source.purchases[2];
this->type = source.type;
}
//overloaded assignment operator=
Customer& Customer::operator= (Customer& otherCustomer)
{
cout << "Overloaded assignment operator= called" << endl;
//self-assignment guard
if (this == &otherCustomer)
return *this; //refernce to the same object
// copy data from the source (rhs) to this object (the destination)
name = otherCustomer.name;
//must make a new scores object to store a copy of the other student
if (purchases != nullptr)
delete[] purchases;
purchases = new int[3];
for (int i = 0; i < 3; i++) {
purchases[i] = otherCustomer.purchases[i];
}
//return this existing object so we can chain this operator
return *this;
}
string Customer::save()
{
stringstream out;
out << this->customerID << ";";
out << this->title << ";";
out << this->name << ";";
out << this->type << ";\n";
out << this->numOfPurchases << ";";
int* purchases = 0;
out.flush();
return out.str();
}
void Customer::parse(string line)
{
stringstream in(line);
string customerIDLine;
getline(in, customerIDLine, ';');
customerID = stoi(customerIDLine);
getline(in, title, ';');
getline(in, name, ';');
getline(in, type, ';');
string numOfPurchases;
getline(in, numOfPurchases, ';');
int s = stoi(numOfPurchases);
int* purchasesArray = new int[3];
purchasesArray[0] = (s & (255 << 16)) >> 16;
purchasesArray[1] = (s & (255 << 8)) >> 8;
purchasesArray[2] = s & 255;
}
void Customer::addCustomer(vector<Customer>& customers )
{
//after read data
int customerID;
cout << "Please Enter Customer ID: " << endl;
cin >> customerID;
string title;
cout << "Please Enter Title: " << endl;
getline(cin, title);
string name;
cout << "Please Enter Name: " << endl;
getline(cin, name);
string type;
cout << "Please Enter Type: " << endl;
getline(cin, type);
int numOfPurchases;
cout << "Please Enter Number of Purchases: " << endl;
cin >> numOfPurchases;
int purchase1;
cout << "Please Enter First Purchase: " << endl;
cin >> purchase1;
int purchase2;
cout << "Please Enter Second Purchase: " << endl;
cin >> purchase2;
int purchase3;
cout << "Please Enter Third Purchase: " << endl;
cin >> purchase3;
Customer c;
customers.push_back(c);
//Customer c();
}
Customer::~Customer() {
cout << "Destructor ~Customer called" << endl;
delete[] purchases;
}
// Overloaded insertion operator (Outputs Character object data as an output stream)
// Defined in header file as a "friend" function, as it is not a member function
//
ostream& operator<<(ostream& out, Customer& customer)
{
cout << "Customer details ( output by insertion operator<< )" << endl;
cout << "Customer ID: " << customer.customerID << endl;
cout << "Title: " << customer.title << endl;
cout << "Name: " << customer.name << endl;
cout << "Number of purchases: " << customer.numOfPurchases << endl;
cout << "Purchases: ";
for (int i = 0; i < 3; i++)
{
if (i > 0) cout << ",";
cout << customer.purchases[i];
}
cout << "Type: " << customer.type << endl;
return out;
}
istream& operator>> (istream& in, Customer& customer)
{
cout << "Enter Customer details ( using the extraction operator>> )" << endl;
cout << "Enter Customer ID: " << endl;
cin >> customer.customerID;
cout << "Enter Title: " << endl;
getline(cin, customer.title);
cout << "Enter Name: " << endl;
getline(cin, customer.name);
cout << "Enter Number of Purchases: ";
cin >> customer.numOfPurchases;
cout << "Enter Purchases: ";
cin >> customer.purchases[0];
cin >> customer.purchases[1];
cin >> customer.purchases[2];
cout << "Enter Type";
getline(cin, customer.type);
cout << endl;
return in;
}
int Customer::getCustomerID()
{
return customerID;
}
string Customer::getTitle()
{
return title;
}
string Customer::getName()
{
return name;
}
int Customer::getNumOfPurchases()
{
return numOfPurchases;
}
int* Customer::getPurchases()
{
return purchases;
}
string Customer::getType()
{
return type;
}
void Customer::setCustomerID(int customerID)
{
if (customerID < 1) {
cout << "Customer ID has to be equal to 1 or more" << endl; //Changed all the "throw invalid_argument" messages to cout as they were causing an issue with my main.cpp file and an abort message kept appearing every time I ran my main.cpp file.
}
this->customerID = customerID;
}
void Customer::setTitle(string title)
{
if (title.length() < 2) {
cout << "Title has to be more than or equal to 2 characters" << endl;
}
this->title = title;
}
void Customer::setName(string name)
{
if (name.length() < 4) {
cout << "Length of name should be more than or equal to 4 characters" << endl;
}
this->name = name;
}
//Got help ith this on stack overflow as I was using "&&" instead of using "||" for the if statement
void Customer::setNumOfPurchases(int numOfPurchases)
{
if(numOfPurchases <0 || numOfPurchases > 10000){
cout << "Number of purchases should be between 0 to 10000" << endl;
}
this->numOfPurchases = numOfPurchases;
}
void Customer::setPurchases(int purchase1, int purchase2, int purchase3)
{
if (purchase1 < 0 || purchase2 < 0 || purchase3 < 0) {
cout << "Purchases must be more than or equal to zero" << endl;
}
}
//Got help from stack overflow on comparing strings as I originally didnt use "type.compare"
void Customer::setType(string type) {
if (type.compare("New") !=0 || type.compare("Either") !=0) {
cout << "Type of purchase has to be New or Either" << endl;
}
}
Code from Customer.h:
#pragma once
#include<iostream>
using namespace std;
#include<string>
#include <vector>
class Customer
{
private:
int customerID;
string title;
string name;
int numOfPurchases;
int* purchases;
string type;
public:
Customer(); // default constructor
Customer(int customerID, string title, string name, int numOfPurchases, int purchase1, int purchase2, int purchase3, string type);
//copy overload assignment
Customer& operator=(Customer& otherCustomer);
Customer(const Customer& source);
string save();
void parse(string line);
void addCustomer(vector<Customer>& customers);
~Customer(); //destructor
//Getters and Setters
void setCustomerID(int customerID);
void setTitle(string title);
void setName(string name);
void setNumOfPurchases(int numOfPurchases);
void setPurchases(int purchase1, int purchase2, int purchase3);
void setType(string type);
int getCustomerID();
string getTitle();
string getName();
int getNumOfPurchases();
int* getPurchases();
string getType();
void printCustomer() {
cout << customerID << "," << title << "," << name << "," << numOfPurchases << "," << purchases << "," << type << endl;
}
friend std::ostream& operator<<(std::ostream& out, Customer& customer); // overloaded operator<<
friend istream& operator>> (istream& in, Customer& customer); // overloaded operator >>
};
Vectors hold objects. If you have an object outside of the vector there is no way to have that same object inside the vector. You can move from one instance to one in the vector (that will move the instances inner parts, but there are still two instances). push_back does make a copy of its parameter when it cannot be moved from.
As you have a constructor that takes all necessary parameters, you can use emplace_back to avoid the copy and construct the instance right in place in the vector:
customers.emplace_back( customerID, title, name, numOfPurchases, purchase1, purchase2, purchase3, type);
If you check reference on std::vector<T,Allocator>::push_back object can be added to vector either by being copied (option1) or being moved (option 2).
So you can create a move constructor for your customer class:
class_name ( class_name && );
And then call push_back using that move consturctor (option 2) on vector:
void push_back( T&& value );
The std::vector<Customer> holds the element by value so just using std::vector::push_back will copy your local object into the vector.
To mitigate this you could either implement move semantics and move the the Customer object like this:
#include <utility>
....
Customer c;
c.parse(line);
customers.push_back(std::move(c));
or construct the object in-place:
// Post c++17 you could use `push_back()` here as well as
// c++17 has mandatory copy elision.
customers.emplace_back(Customer{}); // or customers.emplace_back(); only
customers.back().parse(line);
Both solutions require c++11.
You could also store a reference/pointer and allocate the object on the heap.
std::vector<std::unique_ptr<Customer>> customerVector;
customer_vector.push_back(std::make_unique<Customer>());
// or customer_vector.push_back(std::make_shared<Customer>());
Or
std::vector<Customer*> customerVector;
// Beware for memory leaks, needs to be deleted.
// Basically never use code like this post c++11).
customer_vector.push_back(new Customer{});
I need to create a class of Students where I need to store their name, surname and subjects that they have in uni. How do I need to assign different subjects to different students? User should input it from console. What my class and input should look like? Heres is the code I have so far For example: there are two students Mark Jacobs and John Johny. Mark has 3 subjects: Math, Physics, Geography and John only has 2 Math and Economy.
#include <iostream>
using namespace std;
class Student{
private:
string name;
string surname;
int courseNo;
string subjects[100];
public:
Student(string name = "empty", string surname = "empty")
{
this->name = name + surname;
}
~Student(){
}
void setFullName(string name, string surname){
this->name = name;
this->surname = surname;
}
string getFullName(){
return name + " " + surname;
}
void setSubject(string subjects[100]){
this->subjects[90] = subjects[90];
}
string getSubject(){
return subjects[90];
}
string toString() const
{
return "Studentas: " + this->name;
}
};
int main() {
int number_of_students;
int number_of_subjects = 0;
int choice;
string subjects[90];
string name;
string surname;
cout << "Enter number of students: ";
cin >> number_of_students;
Student Studentas[number_of_students];
cout << "Enter " << number_of_students << " students names and surnames: " << endl;
for (int i = 0; i < number_of_students; i++) {
cin >> name >> surname;
Studentas[i].setFullName(name, surname);
}
for (int i = 0; i < number_of_students; i++) {
cout << i+1 << " Student: " << Studentas[i].getFullName() << endl;
}
cout << "Choose which students subjects you want to enter: ";
cin >> choice;
if(choice == 1){
cout << "Enter " << Studentas[choice-1].getFullName() << " number of subjects: ";
cin >> number_of_subjects;
for (int i = 0; i < number_of_subjects; i++) {
cin >> subjects[i];
Studentas[choice-1].setSubject(subjects);
}
cout << "Studying subjects are: " << endl;
for(int i = 0; i < number_of_subjects; i++){
cout << Studentas[choice-1].getSubject() << endl;
}
}
return 0;
}
I have taken your code changed a little bit, I hope this is what you are looking for
Code:
#include <iostream>
#include <vector>
using namespace std;
class Student {
private:
string name_;
string surname_;
int courseNo_;
std::vector<string> subject_list_;
public:
Student(string name = "empty", string surname = "empty")
{
name_ = name + surname;
}
void setFullName(string name, string surname) {
name_ = name;
surname_ = surname;
}
string getFullName() {
return name_ + " " + surname_;
}
void setSubject(string subject) {
subject_list_.push_back(subject);
}
const std::vector<string>& getSubjects() {
return subject_list_;
}
string toString() const
{
return "Student as: " + name_;
}
};
int main() {
std::vector<Student> student_list;
int number_of_students;
int number_of_subjects = 0;
int choice;
string subject;
string name;
string surname;
cout << "Enter number of students: ";
cin >> number_of_students;
cout << "Enter " << number_of_students << " students names and surnames: " << endl;
for (int i = 0; i < number_of_students; i++) {
cin >> name >> surname;
student_list.push_back(Student(name, surname));
}
int i = 1;
for (auto student : student_list) {
cout << i++ << " Student: " << student.getFullName() << endl;
}
cout << "Choose which students subjects you want to enter: ";
cin >> choice;
if (choice <= number_of_students) {
choice -= 1;
cout << "Enter " << student_list[choice].getFullName() << " number of subjects: ";
cin >> number_of_subjects;
for (int i = 0; i < number_of_subjects; i++) {
cin >> subject;
student_list[choice].setSubject(subject);
}
cout << "Studying subjects are: " << endl;
const auto& subject_list = student_list[choice].getSubjects();
for (auto& subject : subject_list){
cout << subject << endl;
}
}
return 0;
}
I'm finishing a project with a class and will have to have it output my information. I keep getting an error with line 33 saying 'Human : undeclared identifier'.
Here is my full program:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int height;
int weight;
int age;
string name;
cout << "Please enter your name: ";
cin >> name;
cin.clear();
cout << endl;
cout << "Please enter your height (in inches): ";
cin >> height;
cin.clear();
cout << endl;
cout << "Please enter your weight (in whole pounds): ";
cin >> weight;
cin.clear();
cout << endl;
cout << "Please enter your age (in whole years): ";
cin >> age;
cin.clear();
cout << endl;
Human myHuman;
myHuman.editHeight(height);
myHuman.editAge(age);
myHuman.editWeight(weight);
myHuman.editName(name);
cout << "Your description: ";
cout << endl;
myHuman.outputDescription();
return 0;
}
class Human
{
public:
Human();
int getAge();
void editAge(int a);
int getHeight();
void editHeight(int h);
int getWeight();
void editWeight(int w);
string getName();
void editName(string in);
void outputDescription();
private:
int m_age;
int m_height;
int m_weight;
string m_name;
};
string Human::getName()
{
return m_name;
}
void Human::editName(string in)
{
m_name = in;
}
int Human::getAge()
{
return m_age;
}
void Human::editAge(int a)
{
m_age = a;
}
int Human::getHeight()
{
return m_height;
}
void Human::editHeight(int h)
{
m_height = h;
}
int Human::getWeight()
{
return m_weight;
}
void Human::editWeight(int w)
{
m_weight = w;
}
void Human::outputDescription()
{
cout << "Hello " << m_name << " you are " << m_height << " inches tall and weigh " << m_weight
<< " pounds, and are currently " << m_age << " years old.";
}
If anyone could shine some light on this for me, that would be great. I appreciate the help!
I'm creating a text-based adventure game and Im a bit confused on how to actually assign a weapon object to a player. I'm inputting weapons from a text file called weapons.txt:
ID: 1.
Weapon Name: Katana.
Damage: 20.
Weight: 6.
ID: 2.
Weapon Name: Longsword.
Damage: 17.
Weight: 9.
ID: 3.
Weapon Name: WarAxe.
Damage: 22.
Weight: 20.
ID: 4.
Weapon Name: Staff.
Damage: 9.
Weight: 6.
And I have written a player and weapons class:
#include "Weapons.h"
#include <iostream>
#include <string>
using namespace std;
DoublyLinkedList<Weapons> weaponsList;
DoublyLinkedListIterator<Weapons> itr = weaponsList.getIterator();
Weapons :: Weapons() {
this->weaponID = 0;
this->weaponName = "";
this->damage = 0;
this->weight = 0;
}
Weapons :: Weapons(int weaponID,string weaponName,int damage,int weight) {
this->weaponID = weaponID;
this->weaponName = weaponName;
this->damage = damage;
this->weight = weight;
}
int Weapons :: getWeaponID() {
return weaponID;
}
string Weapons :: getWeaponName() {
return weaponName;
}
void Weapons::setWeaponName(string weaponName) {
this->weaponName = weaponName;
}
int Weapons :: getDamage() {
return damage;
}
int Weapons :: getWeight() {
return weight;
}
void Weapons :: getWeapons() {
string fileName = "Weapons\\Weapons.txt";
ifstream infile(fileName);
string garbage;
int id;
string weapon;
int damage;
int weight;
while(infile >> garbage >> id >> garbage >> garbage
>> garbage >> weapon >> garbage >> damage >> garbage
>> garbage >> weight >> garbage) {
cout << "ID: \t\t\t"<< id << "\n";
cout << "Weapon Name: \t\t"<< weapon << "\n";
cout << "Damage: \t\t" << damage <<"\n";
cout << "Weight: \t\t" << weight << "\n";
Weapons w1 (id,weapon,damage,weight);
weaponsList.Append(w1);
}
}
void Weapons :: printWeapons() {
int index = 0;
//Loop through the iterator.
for(itr.Start();itr.Valid();itr.Forth()) {
index++;
cout << "------------------Weapon------------------\n";
cout << "--------------------------------\n";
cout << "Position:\t\t" << index << "\n";
cout << "--------------------------------\n";
cout << "Weapon ID:\t\t" << itr.Item().getWeaponID() << "\n";
cout << "Weapon Name:\t\t" << itr.Item().getWeaponName() << "\n";
cout << "Damage:\t\t\t" << itr.Item().getDamage() << "\n";
cout << "Weight:\t\t\t" << itr.Item().getWeight() << "\n";
cout << "------------------------------------------\n";
}
cout << "Weapons: \t\t" << weaponsList.getCount() << "\n";
}
#include "Player.h"
#include "Validators.h"
#include <iostream>
Validators validators;
//--------------------------------------------------------------------------------------
// Name: Default Constructor.
//--------------------------------------------------------------------------------------
Player :: Player() {
this->firstName = "";
this->secondName = "";
this->level = 0;
this->experience = 0;
this->strength = 0;
this->weapons = weapons;
}
//--------------------------------------------------------------------------------------
// Name: Full Constructor.
//--------------------------------------------------------------------------------------
Player :: Player(string firstName,string secondName,int level,int experience,int strength,Weapons weapons) {
this->firstName = firstName;
this->secondName = secondName;
this->level = level;
this->experience = experience;
this->strength = strength;
this->weapons = weapons;
}
//--------------------------------------------------------------------------------------
// Name: Getters.
// Description: Makes you able to access the member variables of the player class.
//--------------------------------------------------------------------------------------
string Player :: getFirstName() {
return firstName;
}
void Player:: setFirstName(string firstName) {
this->firstName = firstName;
}
string Player :: getSecondName() {
return secondName;
}
int Player :: getLevel() {
return level;
}
int Player :: getExperience() {
return experience;
}
int Player :: getStrength() {
return strength;
}
void Player :: playerCreation() {
string inputFirstName = "Please enter your first name: ";
firstName = validators.getString(inputFirstName);
string inputSecondName = "Please enter your second name: ";
secondName = validators.getString(inputSecondName);
level = 0;
experience = 0;
strength = 8;
weapons.getWeaponName();
}
void Player::loadPlayer() {
//string fileName = "Players\\" + getFirstName()+ getSecondName() + ".txt";
string fileName = "Players\\ConorPendlebury.txt";
ifstream infile(fileName);
string garbage;
string loadFirstName;
string loadLastName;
int loadLevel;
int loadExperience;
int loadStrength;
Weapons weapons;
while(infile>>garbage,infile>>garbage,infile>>loadFirstName,infile>>garbage,
infile>>garbage,infile>>loadLastName,infile>>garbage,infile>>loadLevel,
infile>>garbage,infile>>loadExperience,infile>>garbage,infile>>loadStrength,infile>>garbage) {
cout << "First Name: \t"<< loadFirstName << "\n";
cout << "Second Name: \t"<< loadLastName << "\n";
cout << "Level: \t\t" << loadLevel <<"\n";
cout << "Experience: \t" << loadExperience << "\n";
cout << "Strength: \t" << loadStrength << "\n";
}
//this->setFirstName(firstName);
}
void Player::savePlayer() {
string fileName = "Players\\" + getFirstName()+ getSecondName() + ".txt";
cout << "File: \t\t" << fileName << " was saved" << endl;
ofstream oFile(fileName);
oFile << "First Name: " << this->getFirstName() << endl;
oFile << "Second Name: " << this->getSecondName() << endl;
oFile << "Level: " << this->getLevel()<< endl;
oFile << "Experience: " << this->getExperience()<< endl;
oFile << "Strength: " << this->getStrength()<< endl;
oFile << "Weapon: " << weapons.getWeaponName();
}
I am able to take the weapons from the file and add them to a Linkedlist but I'm stuck on how to assign certain weapons to the player before and after run-time.
Please can anybody help? Thanks.