c++ Constructor With 1 string parameter into 3 attributes [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Some backstory...
For a homework assignment in my Data struct and algorithms,(early on) I have to create a class definition and implementation that models a store item, formatted with Part number, department code, and price. I have it mostly done except for one constructor overload that I can't seem to figure out how to start. Sample of what I have so far.
/** Default Construct*/
Item() : Part_Num("------"), Dep_Code("---"), item_Price(0){}
/** First 3Param Constructor*/
Item(std::string partNum, std::string dept, std::string priceStr):
Part_Num(partNum),Dep_Code(dept), item_Price(stod(priceStr)){}
/** Second 3Param Constructor*/
Item(std::string partNum, std::string dept, double priceD) :
Part_Num(partNum), Dep_Code(dept), item_Price(priceD) {}
The issue I have, is that I need to create a one parameter constructor that takes a string, in the format of
BN3782 ELE 87.25
and splits it into the correct data members. I have an idea for the parsing, but I don't know how to define the constructor to start. Just a push in the right direction would be appreciated. This is my first post and I'm not great at explaining, so let me know if anyone needs any additional information.
I have tried
Item(std::string data) : Part_Num(data), Dep_Code(data), item_Price(data){}
But that has yet to work with my code, and I'm not sure why it would... (was suggested on another forum).
EDIT: I got it working with pm100 suggestion, Here's a code sample I got working for anyone in the future having the same problem.
Item(std::string line) {
item_Data = line;
line = removeSpaces(item_Data);
Part_Num = line.substr(0, 6);
Dep_Code = line.substr(6, 3);
item_Price = stod(line.substr(9));
}

You need to code the field assignments
Item(std::string &valstr)
{
Part_Num = <parsed bit of string>;
Dep_Code = <a different part of the string>;
}

For the sake of completeness, if you like you can still use the initilizer list. You just need to do the parsing somewhere. Lets say you have a:
std::string nth_part(int n,std::string s) { ... }
Then your constructor could be
Item(std::string s) :
Part_Num(nth_part(0,s)), Dep_Code(nth_part(1,s)), item_Price(nth_part(2,s)) {}
However, this would require you to process the string 3 times (which you dont need if you do it in the constructor body). Using the initializer list is good practise, but not always it really pays off.

Item(std::string data)
{
int i=0;
int counter=0;
std::string temp="";
int len=data.length();
while(i<len)
{
if(data[i]!=' ' && i<len-1)
{
temp+=data[i];
}
else
{
if(counter==0) Part_Num=temp;
else if(counter==1) Dep_Code=temp;
else
{
temp+=data[i];
item_price=stod(temp);
}
++counter;
temp="";
}
++i;
}
}
this will give you the desired result for your problem, you can check it by running.

Related

C++ serializing an object containing an array of other objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have the object listed below.
class Customer
{
private:
std::string customerName;
std::string customerLastName;
std::string customerIdentityNumber;
std::vector<std::unique_ptr<Account>> customerAccounts;
}
How would one go about serializing this object? I've tried finding examples but these are all using some complex libraries. Surely there must be an easier way?
Coming from Java this is new to me.
I really recommend a serialization library such as boost::serialization
Its a great library, easy to use, extremely fast, and has much more than just this!
It's exactly what you're looking for.
I prefer a very simple and basic implementation. Lets assume that Serialize() function has already been implemented for Account class.
The implementation of Serialize() function of Customer class can be:
void Customer::Serialize(Archive& stream)
{
if(stream.isStoring()) //write to file
{
stream << customerName;
stream << customerLastName;
stream << customerIdentityNumber;
stream << customerAccounts.size(); //Serialize the count of objects
//Iterate through all objects and serialize those
std::vector<std::unique_ptr<Account>>::iterator iterAccounts, endAccounts;
endAccounts = customerAccounts.end() ;
for(iterAccounts = customerAccounts.begin() ; iterAccounts!= endAccounts; ++iterAccounts)
{
(*iterAccounts)->Serialzie(stream);
}
}
else //Reading from file
{
stream >> customerName;
stream >> customerLastName;
stream >> customerIdentityNumber;
int nNumberOfAccounts = 0;
stream >> nNumberOfAccounts;
customerAccounts.empty(); //Empty the list
for(int i=0; i<nNumberOfAccounts; i++)
{
Account* pAccount = new Account();
pAccount->Serialize(stream);
//Add to vector
customerAccounts.push_back(pAccount);
}
}
}
The code is self-explanatory. But idea is to archive count and then every element. This help while deserializing from file.

How do I use get and set methods in c++ with an object that is initialised with new [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Im trying to use get and set methods within c++ with an object that is initialised with new
Person *Person1 = new Person;
string first;
string family;
string ID;
int birth;
anyone any idea how I do this?
Assuming that your Person has member functions like getFirst() you would use the dereference operator (-> or *) like this:
Person1->getFirst(); // equivalent to (*Person1).getFirst()
You need to define the setters and getters in your class, as well as you should define your members there
something like:
class person{
public:
person(){}
~person(){}
here put your getter and setter like...
void setFirst(...) { .... }
string getFirst() { return ... }
...
private:
string first;
string family;
string ID;
int birth;
}

How to allow a program to create new objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Thanks so much for taking the time to look at my question!
Right now I am working with classes and objects. I am trying to write a program that stores information about visitors to a hotel. A user will input the name of the visitor and some information about them. The program will then store that information in an object and be able to calculate how much to charge for the users stay.
The problem that I am running into is that I don't know how to let the program create new objects for the visitors. For example, if Sally came in I would like to create a new object for her within the program that could store her information.
I have looked at dynamic object creation and done a fair amount of Googling on the subject but can't seem to find any answers. Here is a simplified version of what I would like to do:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class visitor {
public:
string name;
int age;
};
int main()
{
//a new person comes to the hotel, the person at the desk gives the program his/her name
//and age and it is put into a class so it can be used later.
}
If there is a better way to accomplish this I would love suggestions, I am but a fledgling programmer and it is very possible that I am approaching this incorrectly.
Thanks in advance!
You have done fine, so far.
class visitor {
public:
string name;
int age;
};
int main()
{
//a new person comes to the hotel, the person at the desk
//gives the program his/her name
//and age and it is put into a class so it can be used later.
}
Now remember how easy it is to define a integer value i, and initialize it with 0:
int i = 0;
Your class is just like "int". So name a variable declared just like int.
visitor guest1;
You should write a default ctor to initialize the contents. Note that your code has a default ctor provided by the compiler. But what it does (nothing) is not terribly useful.
And then write a non-default ctor to fill in the contents.
and so on, and so on.
How about a show method to display values.
guest1.show();
Good luck.
You need to create a constructor. This is a function that constructs visitors. We write that as follows:
class Visitor {
public:
string name;
int age;
Visitor(string name, int age) {
this->name = name;
this->age = age;
}
};
We can then create a new Visitor object (note that its usual convention to make a class name's first letter uppercase) with the following:
Visitor sally = Visitor("Sally", 22);
To allow the user to input what we want the name and age to be, you should look at another SO answer like Getting user input in C++.
EDIT: You don't need to create a constructor as the compiler will make one by default in this case, but it will be useful for you to learn by creating your own constructors for the time being, so you know what's happening.

Operations with objects - Practicing for the exam - OOP [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 7 years ago.
Improve this question
Current state of my solution
#include <iostream>
class money {
int kn, lp;
public:
void add(int kn, int lp){
this->kn+=kn;
this->lp+=lp;
if(this->lp>=100){
this->kn++;
this->lp-=100;}
}
void print() {
std::cout<<this->kn<<" kuna";
if(this->lp!=0) std::cout<<", "<<this->lp<<" lipa";
}
};
int main () {
//money a(7, 50) , b(3, 70) , c(2, 80);
money a;
//simplified
a.add(3, 70);
a.add(2, 80);
a.print();
}
Task requires me to expand the class, so that the below program correctly adds the money and prints it. http://prntscr.com/711bs5
I simplified the task, because I'm still getting to the final solution. But I don't know why does it print garbage? And after I solve that.
Can someone help me in short tips, what's needed to correctly solve the task. Obviously when I'm instancing those objects, I'm supposed to add to object a, the values from objects b and c. But I don't know how to do that, I missed a few lessons.
EDIT: Why do people downvote? Am I missing something? Too trivial question? Bad title?
For the first part: initialize.
For the second part you have to create a method taking another instance of class money as a parameter and add the values of kn and ln to the ones of the existing.
#karma:
It's not a formula, but there is no check how money values have to be entered.
The smartest thing in my opinion would be to check the correct behavior while instancing an object (in the constructor), so that objects can only be of form:
0<=lp<=99;
edit2:
How do you create this method?
For ones, since your add method already exists you can OVERLOAD it. This means you create a method with the same name and return type, but having different parameters.
So you can create another method add and pass a money instance to it, as already mentioned. If you don't understand that, you should really have a look at how methods work and how to create them and that basically anything can be passed to them (not just primitive types).
You need to initialize the variables before you use them.
When you use variables without initializing them, you get garbage values. For instance, here:
this->kn+=kn;
this->lp+=lp;
both of them are uninitialized.
For data members of a class, you can initialize using a constructor as follows:
money()
{
kn=0; lp=0;
}
So, your code now becomes:
#include <iostream>
class money {
int kn, lp;
public:
money()
{
kn=0; lp=0;
}
void add(int kn, int lp){
this->kn+=kn;
this->lp+=lp;
if(this->lp>=100){
this->kn += this->lp/100; this->lp %= 100;}
}
void print() {
std::cout<<this->kn<<" kuna";
if(this->lp!=0) std::cout<<", "<<this->lp<<" lipa";
}
};
int main () {
//money a(7, 50) , b(3, 70) , c(2, 80);
money a;
//simplified
a.add(3, 70);
a.add(2, 80);
a.print();
return 0;
}

How do i change an object through the use of pointers?

#include "Visit.h"
class Patient
{
private:
std::string name;
std::string IC;
List<Visit> *visitList;
List<MC> mcList;
public:
Patient();
Patient(std::string, std::string);
void addVisit(Visit);
List<Visit> *getVisitList();
};
//End of Patient.h
#include "Patient.h"
Patient::Patient()
{
visitList = new List<Visit>();
}
Patient::Patient(std::string ic, std::string n) : name(n), IC(ic)
{
visitList = new List<Visit>();
}
void Patient::addVisit(Visit v)
{
visitList->add(v);
}
List<Visit> * Patient::getVisitList()
{
return visitList;
}
//End of Patient.cpp
class Visit
{
private:
__int64 time;
double cost;
bool xRayStatus = false;
public:
Visit();
Visit(__int64, double);
void addXRay();
bool getXRayStatus();
};
//End of Visit.h
#include "Visit.h"
Visit::Visit() {
}
Visit::Visit(__int64 t, double c) : time(t), cost(c) {
}
void Visit::addXRay()
{
xRayStatus = true;
}
bool Visit::getXRayStatus()
{
return xRayStatus;
};
//End of Visit.cpp
int main()
{
int pos;
Visit v(/*current time, cost*/);
Patient p()
unordered_map<string, Patient> patientMap;
string IC;
getline(cin,IC);
Patient p(IC, "John");
patientMap.insert({IC, p});
Patient *pc;
Visit *vc;
pos = patientMap[IC].getVisitList()->getLength();
pc = &patientMap[IC];
pc->addVisit(v); //Debugger shows patientMap[IC].getVisitList()->getLength() becomes 2
pc->getVisitList()->get(pos).addXRay(); //patientMap[IC].getVistList()->get(0).getXRayStatus() still false
vc = &patientMap[IC].getVisitList()->get(pos);
vc->addXRay(); //patientMap[IC].getVistList()->get(0).getXRayStatus() still false
}
How do i make that getXRayStatus true? It seems odd to me that i can add items into the list but not carry out other functions like vc->addXRay.
vc itself shows true but the change isn't reflected on my map.
pc somehow is able to add Visits and show the change on the map.
In the List<Visit> you are keeping instances of Visits. When you are setting the xRayStatus you are changing the status of the local Visit copy you get from the list, not to the actual object in the list.
In an extended comment conversation, the asker has asked for general redesign help to avoid the problems caused by working with a Visit copy from get(). My redesign suggestions are:
stop using List. Whether you wrote it yourself or got it somewhere else, it's surely more than you need. Use std::vector<> as the collection class of first choice, and change to something else only when you need it.
don't keep pointers to your collections in Patient unless they are likely to be enormous memory hogs. Have vectors as member variables. This will save you having to write a lot of cleanup code.
Stop keeping solid Visit objects in the collections. Use make-shared() or make_unique to get yourself smart pointers to visit objects that are on the heap. Keep these pointers in the vectors and you can deference them to change the real values in the real visits out on the heap
consider adding a date and time or visit number to Visit since at the moment it's not clear to me how you find a specific visit when there is more than one
set properties in things before you put them in collections. Your main knows all about the inside of a Visit (not that I approve of that) but has Patient create an empty one and then jumps through hoops trying to get hold of it and change some of its properties. Why not have Patient set those properties? Or have main() create a Visit, fill in all the properties, and then hand it to Patient saying "here, add this to your collection"? What you're doing now is so much harder than it needs to be.
Finally, find a tutorial, book, or online course that works for you and gets you clear on the difference between objects and pointers, good reasons for using pointers, the need for destructors (you have none at the moment) and for good measure explains the collection classes in std:: and elsewhere. Tutorials and architectural advice are not a good fit for the Q&A mechanism of StackOverflow.