Why can't i do like this? In the below code, I can access from for loop, but not from outside loop?
class root
{
string name;
public:
root()
{
}
root(const string& okay)
{
name = okay;
}
void setRoot(const string& okay)
{
name = okay;
}
string getRoot()
{
return name;
}
~root ()
{
}
}; // class root
int main()
{
string a;
vector<root> Root;
vector<root>::iterator oley;
root okay;
for (int i=0; i<5;i++) //this is to add strings in vector
{
cin >> a;
okay.setRoot(a);
Root.push_back(okay);
}
for (oley=Root.begin(); oley!=Root.end(); oley++) //this is to print vectors in scren
{
cout << (*oley).getRoot() << endl;
}
oley = Root.begin();
cout << (*oley + 2).getRoot(); //this is error. What is required to make it legal?
return 0;
}
So, if we can access iterator from for loop, why can't we do so in non-looped codes?
cout << (*oley + 2).getRoot();
This is because of C++ operator precedence, *oley+2 is interpreted as (*oley) + 2 which is becomes root + 2
update
cout<<(*oley+2).getRoot();
to
cout<<(*(oley+2)).getRoot();
or
cout<<oley[2].getRoot();
Related
3.) string getFirstName(int ind) const: An accessor method that takes the user index and returns his/her first name.
This is the problem im working on towards my program and as it says above im supposed to use an accessor method that takes the user index and returns his/ her first name???
Here is my code so far but im very confused how to go about using a accessor method
string RatingDB::getFirstName(int ind) const
{class getFirstName;
{
public:
return "";
}
}
For reference here is my program code so far
// TODO: implement all these method stubs!
void RatingDB::loadFile(string filename)
{
ifstream OpenFile;
OpenFile.open (filename);
// if this file does not exist then end the program
if (!OpenFile.is_open())
{
cout << "can't open this file!" << endl;
exit(EXIT_FAILURE);
}
int i = 0;
char c;
while(! OpenFile.eof())
{
do {
c=OpenFile.get();
if(c!= ' ')
m_firstNames[i].push_back(c);
} while(c!= ' ');
do {
c=OpenFile.get();
if(c!= ' ')
m_lastNames[i].push_back(c);
}while(c!= ' ');
do {
c=OpenFile.get();
if(c!= '/n' && OpenFile.eof())
m_Ratings[i].push_back(c);
} while(c!= '/n' && OpenFile.eof());
i++;
}
}
string RatingDB::getFirstName(int ind) const
{class getFirstName;
{
public:
return "";
}
}
string RatingDB::getLastName(int ind) const
{
return "";
}
vector<int> RatingDB::getRatingVector(int ind) const
{
return vector<int>();
}
int RatingDB::getNumberOfUsers() const
{
return -1;
}
void RatingDB::insertRating(string firstName, string lastName, string strRatings)
{
}
void RatingDB::displayRatings() const
{
}
int RatingDB::compareRatings(const vector<int>& RatingVector1, const vector<int>& RatingVector2) const
{
return -1;
}
void RatingDB::findSimUsers(const vector<int>& ratingVector, vector<int>& friendVector, vector<int>& scoreVector)
{
}
vector<int> RatingDB::parseVectorString(string strRatings)
{
return vector<int>(1);
}
//************************************************************************************************************************
void RatingDB::findTenBestMatches(const vector<int>& RatingVector, vector<int>& returnVector)
{
vector<int> sortVector(getNumberOfUsers()); //create a vector of integers representing each index in your vector of structures
bool swapped; //a boolean to indicate if any swaps have been made during this pass of the loop.
for(int i = 0; i < getNumberOfUsers(); i++) //initialize the array so that we have an integer indicating the location in
sortVector[i] = i; //your structure vector for every user that is read in.
do{ //keep doing the following if we swap at least once during the pass
swapped = false; //set the swapped variable for this pass
for(int i = 0; i < getNumberOfUsers() - 1; i++) //we are going to look at each element in the vector and see if it has a ranking lower
{ //than the next element. If so, the two need to be swapped.
if(compareRatings(RatingVector, getRatingVector(sortVector[i])) < compareRatings(RatingVector, getRatingVector(sortVector[i + 1])))
{ //we compare the two rankings and swap the two in the array if the first is lower than the second
//(we want the best rankings first)
int temp;
temp = sortVector[i]; //swap this one and the next one
sortVector[i] = sortVector[i + 1];
sortVector[i + 1] = temp;
swapped = true; //if we moved anything, then another pass is necessary
}
}
}while(swapped);
for(int i = 0; i < 10; i++) //copy the top ten indexes to the returnVector
if(i < getNumberOfUsers()) //if there are at least 10 users
returnVector.push_back(sortVector[i]); //copy the index
}
You want to change your perspective. Instead of having an array for first names and another for last names, you should put the first and last names into a structure and use a vector of that structure.
class Person
{
std::string m_first_name;
std::string m_last_name;
public:
Person(const std::string& first_name,
const std::string& last_name)
: m_first_name(first_name),
m_last_name(last_name)
{ }
};
typedef std::vector<Person> Person_Container;
int main(void)
{
Person jack("Jack", "Frost");
Person alton("Alton", "Brown");
Person bobby("Bobby", "Flay");
Person_Container people;
people.push_back(jack);
people.push_back(alton);
people.push_back(bobby);
return EXIT_SUCCESS;
}
Edit 1: Input A Person
You can augment the Person class by adding input methods.
class Person
{
std::string m_first_name;
std::string m_last_name;
public:
Person(const std::string& first_name = "",
const std::string& last_name = "")
: m_first_name(first_name),
m_last_name(last_name)
{ }
void Input_From_User(std::istream& inp,
std::ostream& out);
};
void
Person ::
Input_From_User(std::istream& inp, std::ostream& out)
{
out << "Input first name:\n";
std::getline(inp, first_name);
out << "\nInput last name:\n";
std::getline(inp, last_name);
}
int main(void)
{
Person somebody;
somebody.Input_From_User(cin, cout);
std::vector<Person> people;
people.push_back(somebody);
return EXIT_SUCCESS;
}
Likewise, you can augment the Person class for output as well.
That, is left as an exercise for the reader. :-)
I'm currently writing a program that will help a college keep track of which students are in what clubs. This code will be pasted into existing code that works, as provided by my professor.
Could someone please look my code over, and help me work through my mistakes? I included comments to explain what everything should do.
Also, please note this is an assignment and I cannot change anything about the class. I'm also a beginner, so keep it simple, please. Your help will be extremely appreciated beyond all measure.
class Club
{
public:
Club();
Club(Club &c);
Club(string cname);
void addMember(string name);
void removeMember(string name);
string getClubName() const;
string setClubName(const string& nameOfClub);
void loadClub();
bool isMember(string& name) const;
string getAllMembers() const;
friend Club mergeClubs(Club& c1, Club& c2);
~Club();
private:
string *members;
int numMembers;
string clubName;
};
Club::Club()
{
clubName = "";
numMembers = 0;
}
Club::Club(Club &c)
{
numMembers = c.numMembers;
members = new string [numMembers];
for (int i = 0; i < numMembers; i++)
{
members[i] = c.members[i];
}
//copy constructor
//watch out for memory leaks
}
Club::Club(string cname)
{
clubName = cname;
//cname should be saved as the club's name in the clubName variable
}
void Club::addMember(string name)
{
string *m;
m = new string [numMembers];
string *members = m;
for (int i = 0; i < numMembers; i++)
{
for (int j = 0; j < name.length(); i++)
{
m[i] = name[j];
}
}
delete [] m;
//adds new member to the club
//records their name in the members variable
//may need a dynamic array to make this work, watch for memory leaks!
}
void Club::removeMember(string name)
{
string *m;
m = new string [numMembers];
string *members = m;
for (int i = 0; i < numMembers; i++)
{
if ( m[i] == name)
{
m[i] = "";
}
}
delete [] m;
//deletes the person from the array in members
//will do nothing if the person is not in the array to begin with
//may require dynamic array to make this work- watch for memory leaks!
//if the person's name appears more than once, just delete the first instance
}
string Club::getClubName() const
{
return clubName;
//getter of clubName
}
string Club::setClubName(const string& nameOfClub)
{
return clubName = nameOfClub;
//setter of clubName
}
void Club::loadClub()
{
//should print "tell me the name of the next member of the club"
//reads into the variable name
//uses addMember() to add that person to the club
//the input should include up to the line break as the name, so it should take in "jane doe" as an entry
//keeps asking for more names until the user enters a blank entry
string name;
do
{
cout << "Tell me the name of the next member of the club, ";
cout << "or submit a blank entry to stopent ering names." << endl;
getline(cin, name, '\n');
addMember(name);
} while (name != "");
}
bool Club::isMember(string& name) const
{
/*for (int i = 0; i < numMembers; i++)
{
for (int j = 0; j < name.length(); j++)
{
if (members[i] == name)
{
return true;
}
else
{
return false;
}
}
}*/
for (int i = 0; i < numMembers; i++)
{
if (members[i] == name)
{
return true;
}
return false;
}
//returns true if the person is a member of the club, false otherwise
}
string Club::getAllMembers() const
{
for (int i = 0; i < numMembers; i++)
{
return members[i];
cout << ", ";
}
cout << endl;
//returns a string of all the names of the members of the club
//commas and spaces separating every entry of the list
//should not be a comma following the last name in the list
}
Club mergeClubs(Club& c1, Club& c2)
{
//creates a new club from 2 existing clubs
//combined club name should be Club 1/Club 2
Club temp;
temp.clubName = c1.clubName + "/" + c2.clubName;
return temp;
}
Club::~Club()
{
delete [] members;
//destructor
//watch out for memory leaks
}
For some reason I cannot fathom I have (mostly) corrected this program for you. There are still some nasty things like passing copies of strings into const functions but fixing these would be mere optimisations. At least this program is logically correct.
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <sstream>
using namespace std;
class Club
{
public:
Club();
Club(const Club &c);
Club(string cname);
void addMember(string name);
void removeMember(string name);
string getClubName() const;
string setClubName(const string& nameOfClub);
void loadClub();
bool isMember(const string& name) const;
string getAllMembers() const;
friend Club mergeClubs(Club& c1, Club& c2);
~Club();
private:
vector<string> members;
string clubName;
};
Club::Club()
: members()
, clubName()
{
}
Club::Club(const Club &c)
: members(c.members)
, clubName(c.clubName)
{
}
Club::Club(string cname)
: members()
, clubName(cname)
{
}
void Club::addMember(string name)
{
members.push_back(name);
}
void Club::removeMember(string name)
{
members.erase(remove(members.begin(), members.end(), name), members.end());
}
string Club::getClubName() const
{
return clubName;
//getter of clubName
}
string Club::setClubName(const string& nameOfClub)
{
return clubName = nameOfClub;
//setter of clubName
}
void Club::loadClub()
{
//should print "tell me the name of the next member of the club"
//reads into the variable name
//uses addMember() to add that person to the club
//the input should include up to the line break as the name, so it should take in "jane doe" as an entry
//keeps asking for more names until the user enters a blank entry
string name;
do
{
cout << "Tell me the name of the next member of the club, ";
cout << "or submit a blank entry to stopent ering names." << endl;
getline(cin, name, '\n');
addMember(name);
} while (name != "");
}
bool Club::isMember(const string& name) const
{
return find(members.begin(), members.end(), name) != members.end();
}
string Club::getAllMembers() const
{
stringstream result;
vector<string>::const_iterator b = members.begin(), e = members.end();
for (bool comma = false ; b != e; ++b, comma = true)
{
if (comma) {
result << ", ";
}
result << *b;
}
return result.str();
}
Club mergeClubs(Club& c1, Club& c2)
{
Club temp(c1.clubName + "/" + c2.clubName);
struct memberAdd {
Club& _club;
memberAdd(Club& club) : _club(club) {}
void operator()(const string& member) {
_club.addMember(member);
}
};
for_each(c1.members.begin(), c1.members.end(), memberAdd(temp));
for_each(c2.members.begin(), c2.members.end(), memberAdd(temp));
return temp;
}
Club::~Club()
{
//destructor
//watch out for memory leaks
}
int main()
{
Club boys("red");
boys.addMember("Ben");
boys.addMember("Paul");
Club girls("blue");
girls.addMember("Lucy");
girls.addMember("Hermione");
Club unisex = mergeClubs(boys, girls);
cout << unisex.getClubName() << " has the following members: " << unisex.getAllMembers() << endl;
}
Some initial comments:
The copy constructor should take a const Club& like this:
Club(const Club& club)
members and numMembers are anachronistic. Use a std::vector for members and drop the numMembers altogether (std::vector has a size() method).
Club::Club does not initialise members or numMembers. This will result in a possible crash in the destrutor. This would be solved if you replaced them with a vector.
the logic in addMember does not make sense.
nor in removeMember
isMember should take a const string& and you would be well advised to write it in terms of std::find() (#include <algorithm>)
I could go on...
for (int i = peekIndex; i < pdp->size(); i++)
{
string x = pdp->peek();
if (x.at(0) == 's')
{
out << pdp->peek() << endl;
pdp->moveForward();
}
else
{
pdp->moveForward();
}
}
The error I get is
terminate called after throwing and instance of std::out_of_range
what(): basic_string::at()
Abort
The peek method returns a string in the position of the peekIndex.
The moveFowrard method increments the peekIndex.
pdp is a vector of size 100. I am supposed to peek and print only words that start with 's' that have been pushed to the <vector>. I am basically done but this part is proving somewhat difficult.
Thanks
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class StringDeque {
protected:
vector<string>* elements;
int frontItem; //CLASS INV: indexes item with least index
int rearSpace; //CLASS INV: indexes space after item with greatest index
int upperBound; //For array[0..n-1] this is "n" not "n-1".
public:
StringDeque(int guaranteedCapacity):
elements (new vector<string>( 2*guaranteedCapacity))
frontItem (guaranteedCapacity),
rearSpace ( guaranteedCapacity),
upperBound ( 2*guaranteedCapacity)
{}
proteted:
virtual bool isEmpty() const { return frontItem == rearSpace; }
virtual bool isFull() const { return rearSpace == upperBound || frontItem == 0; }
virtual int size() const { return rearSpace - frontItem; }
virtual string popRear() {
if (isEmpty()) {
cerr<< "Later we'll define and throw an EmptyQException"<< endl;
return "";
} else {
return elements->at(--rearSpace);
}
}
virtual string popFront() {
if (isEmpty()) {
cerr<<"Later we'll define and throw an EmptyQException"<<endl;
return "";
} else {
return elements->at(frontItem++);
}
}
/** Directions include similarly testing for "full" in the C++ code.
*/
virtual void pushFront(string newItem) {
elements->at(--frontItem)= newItem;
}
virtual void pushRear(string newItem) {
elements->at(rearSpace++) = newItem;
}
virtual string toString() {
string out = "";
for (int i = frontItem; i < rearSpace; i++) {
out += elements->at(i) + " ";
}
return out;
}
};
class PeekDeque : public StringDeque {
private:
int peekIndex;
public:
PeekDeque(int guaranteedCapacity):
StringDeque(guaranteedCapacity),
peekIndex(guaranteedCapacity/2)
{}
virtual void moveFrontward() {
if (peekIndex == upperBound) {
cerr<<"Cannot move past total capacity"<<endl;
} else{
elements->at(peekIndex ++);
}
}
virtual void moveRearward () {
if (peekIndex == -1) {
cerr<<"Cannot move below total capacity"<<endl;
} else{
elements ->at( peekIndex--);
}
}
virtual string popFront() {
cerr<<"Attempt to pop from empty PeekDeque"<<endl;
}
virtual string popRear() {
cerr<<"Attempt to pop from empty PeekDeque"<<endl;
}
virtual string peek() {
if (isEmpty()) {
cerr<<"Cannot peek an Empty index"<<endl;
return "";
} else {
return elements->at(peekIndex + 1);
}
}
virtual string toString() {
string out = "";
for (int i = frontItem; i < rearSpace; i++) {
out += elements->at(i) + " ";
}
return out;
}
};
int main(){
PeekDeque* pdp = new PeekDeque(101);
pdp->pushFront("oh");
pdp->pushFront("say");
pdp->pushFront("can");
pdp->pushFront("you");
pdp->pushFront("see");
pdp->pushRear("any");
pdp->pushRear("bad bugs");
pdp->pushRear("on");
pdp->pushRear("me?");
for(int i = peekIndex; i<pdp->size(); i++){
string x =
if(x.at(0)=='s'){
cout<<pdp->peek()<<endl;
pdp->moveForward(); }
else{
pdp->moveForward();
}
}
}
May be your test should be:
if(!x.empty() && x.at(0)=='s')
I can't tell exactly, without seeing more context, but I'm pretty sure x.empty() is a probable case.
UPDATE:
pdp is a vector of size 100
Are you sure to have used the pdp.resize(100,std::string()); method to ensure all positions are initialized correctly?
it is not empty i have pushed 8 things to pdp
Also std::vector<>::resize() and std::vector<>::push_back() might not work together as you expect. Use either std::vector<>::push_back() or std::vector<>::resize() to give it a pre-allocated size and manipulate entries by index. Always check for std::vector<>::size() for indexed access.
UPDATE 2:
But the real answer is apparently simpler. You have:
virtual string peek() {
if (isEmpty()) {
cerr<<"Cannot peek an Empty index"<<endl;
return ""; // This will certainly result in a string that is empty!
Here's how your container looks like after initial pushes:
0 202
| ... | ... | ... | ... |
^ ^ ^
| | rearSpace
| peekIndex
frontItem
Now, size() returns rearSpace - frontItem, but iteration starts from peekIndex and thus goes beyond rearSpace index, peeking uninitialized (empty) strings.
That's certainly an approximate answer, since your work with indices is a mess. Please be really careful and think it through.
I have a program where I am setting up a closed hash table. In each Element of the Hash table, there is a Student class which holds varies members (name, id, year, etc.). I am simply trying to print out what has been added to my array, but I keep getting a SegFault, and I don't know why. It is only in my print function, though. I have copied the line of code to my other functions or put them in different classes, and they work there, but not when I try to print from my print function. I am at the end of my rope, trying to figure out why I can access the memory location of each member, but not it's actual value.
Here is my program:
main.cpp:
using namespace std;
#include <cstdlib>
#include "hash.h"
int main()
{
string temp1;
string temp2;
string temp3;
string temp4;
string temp5;
string temp6;
Hash h;
do{
cout << "set> ";
cin >> temp1;
//Checking for quit command.
if(temp1.compare("quit") == 0)
{
return 0;
}
//checking for add command.
else if(temp1.compare("add") == 0)
{
cin >> temp2;
cin >> temp3;
cin >> temp4;
cin >> temp5;
cin >> temp6;
Student *s1 = new Student(temp2, temp3, temp4, temp5, temp6);
Element e1(s1);
h.add(e1);
}
//checking for remove command.
else if(temp1.compare("remove") == 0)
{
int r;
cin >> r;
h.remove(r);
}
//checking for print command.
else if(temp1.compare("print") == 0)
{
h.print();
}
//Anything else must be an error.
else
{
cout << endl;
cout << "Error! "<< endl;
}
}while(temp1.compare("quit") != 0);
}
hash.h:
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
// Student Class
class Student{
private:
string firstName;
string lastName;
string id;
string year;
string major;
public:
//Constructor
Student(string a, string b, string c, string d, string e);
friend class Element;
friend class Hash;
};
//Element class
class Element{
private:
Student *data;
public:
int getKey();
Student* getData();
void printStudent();
//Constructor
Element(Student *e)
{
data = e;
};
friend class Hash;
};
class Hash{
private:
Element **array;
public:
void add(Element);
void print();
void remove(int);
//Constructor
Hash()
{
array = new Element *[10];
};
friend class Student;
};
hash.cpp:
#include "hash.h"
//The Constructor for Student
Student::Student(string a, string b, string c, string d, string e)
{
firstName = a;
lastName = b;
id = c;
year = d;
major = e;
}
//getKey function for Element Class
int Element::getKey()
{
int key = atoi(getData()->id.c_str());
return key;
}
Student* Element::getData()
{
return data;
}
void Element::printStudent()
{
string c = data->firstName;
cout<< "(" << c << ")";
}
//The add command
void Hash::add(Element e1)
{
int x = e1.getKey()%10;
int i = 0;
if(array[x] == NULL || array[x]->getData() == NULL)
{
array[x] = &e1;
}
else
{while(array[x] != NULL || array[x]->getData() != NULL)
{
x=(x+(i*i))%10;
if(array[x] == NULL || array[x]->getData() == NULL)
{
array[x] = &e1;
break;
}
else
{
i++;
}
}}
}
//The remove command
void Hash::remove(int n)
{
Element e2(NULL);
for(int j = 0; j<10; j++)
{
if(n == array[j]->getKey())
{
array[j] = &e2;
cout << "true" << endl;
break;
}
}
cout << "false" << endl;
}
//The Print command
void Hash::print()
{ int k = 0;
while(k<10)
{
if(array[k] == NULL)
{
cout << "(NULL)";
}
else if(array[k]->getData() == NULL)
{
cout << "(DEL)";
}
else
{
cout << "(" << array[k]->getData()->firstName << ")";
}
k++;
}
cout << endl;
}
Thank you for your help.
You have dangling pointers.
This function gets a temporary copy of an Element, calling it e1.
//The add command
void Hash::add(Element e1)
{
It then stores the address of this local variable.
array[x] = &e1;
And when Hash::add leaves scope, e1 no longer exists.
}
array[x] now points to memory that is no longer Element e1.
The general problem you are facing is that you have designed a Hash class that maintains pointers to objects, but has little control or knowledge regarding when those objects get destroyed.
You will need to personally ensure that objects added to your Hash last at least as long as the Hash does.
Simplest solution for your problem could be to store Element instances in Hash by value not by pointers. So:
class Hash{
private:
Element *array;
public:
void add(Element);
void print();
void remove(int);
//Constructor
Hash()
{
array = new Element[10];
};
friend class Student;
};
Now when you store new element or remove existing you copy them:
array[x] = e1; // not &e1 anymore
This is not very good practice, but at least could change your program in some workable state with minimal changes.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I am looking to change this from struct to classes and use a header file to hold the class.
What would you suggest in way of changing it over. The code all works. There is no problem there. just a simple change over question.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
struct printype
{
char dots[8][15];
int unknown15; // can have values of 0..127
string serial11_14; // 8 characters 00000000...99999999
int year8; // without century, 0..99
int month7; // 1..12
int day6; // 1..31
int hour5; // 0..23
int minute2; // 0..59
};
int getunknown15(); // prototypes
string getserial11_14();
int getyear8();
int getmonth7();
int getday6();
int gethour5();
int getminute2();
int setunknown15(int); //------------------------- protos
string setserial11_14(string);
int setyear8(int);
int setmonth7(int);
int setday6(int);
int sethour5(int);
int setminute2(int);
// int array and display info for array
void setup(char[8][15]);
// display array
void darray(char[8][15]);
// displays printer information
void dpinfo(printype);
// set parrity
void spar(char[8][15]);
// fill array
void ftarray(printype &); //----------------------end protos
//-------------------------------------
void main ()
{
printype pt;
pt.unknown15=getunknown15();
pt.unknown15=setunknown15(pt.unknown15);
pt.serial11_14=getserial11_14();
pt.serial11_14=setserial11_14(pt.serial11_14);
pt.year8=getyear8();
pt.year8=setyear8(pt.year8);
pt.month7=getmonth7();
pt.month7=setmonth7(pt.month7);
pt.day6=getday6();
pt.day6=setday6(pt.day6);
pt.hour5=gethour5();
pt.hour5=sethour5(pt.hour5);
pt.minute2=getminute2();
pt.minute2=setminute2(pt.minute2);
cout <<"-----------------------------------------------------"<<endl;
cout <<" Lets Get Started"<<endl;
cout <<"-----------------------------------------------------"<<endl;
setup(pt.dots); // sets up the array
dpinfo(pt); // prints out the final array
ftarray(pt);
spar(pt.dots);
darray(pt.dots);
}
int getunknown15()
{
printype tem;
cout <<"-----------------------------------------------------"<<endl;
cout <<" Enter the Unkown Variable (0-127): ";
cin >>tem.unknown15;
cout <<"-----------------------------------------------------"<<endl;
return tem.unknown15;
}
string getserial11_14()//------------------------------------------ starts the get information sets
{
printype tem;
cout <<" Enter the Serial Variable (8char long): ";
cin >>tem.serial11_14;
cout <<"-----------------------------------------------------"<<endl;
return tem.serial11_14;
}
int getyear8()
{
printype tem;
cout <<" Enter the Year Variable (2char long): ";
cin >>tem.year8;
cout <<"-----------------------------------------------------"<<endl;
return tem.year8;
}
int getmonth7()
{
printype tem;
cout <<" Enter the Month Variable (2char long): ";
cin >>tem.month7;
cout <<"-----------------------------------------------------"<<endl;
return tem.month7;
}
int getday6()
{
printype tem;
cout <<" Enter the Day Variable (2char long): ";
cin >>tem.day6;
cout <<"-----------------------------------------------------"<<endl;
return tem.day6;
}
int gethour5()
{
printype tem;
cout <<" Enter the Hour Variable (2char long): ";
cin >>tem.hour5;
cout <<"-----------------------------------------------------"<<endl;
return tem.hour5;
}
int getminute2()
{
printype tem;
cout <<" Enter the Minute Variable (2char long): ";
cin >>tem.minute2;
cout <<"-----------------------------------------------------"<<endl;
return tem.minute2;
}
//-----------------------------------------------------------put functions (adds info to the array)
int setunknown15(int tem)
{
printype pp;
if (tem>127||tem<0)
{
cout << "Error" << endl;
return 0;
}
else
{
pp.unknown15 = tem;
return pp.unknown15;
}
}
string setserial11_14(string tem)
{
printype pp;
if(tem.size() !=8)
{
cout <<"nope.jpg"<<endl;
return 0;
}
else
{
for (int i = 0; i < 8; i++)
{
if(!isdigit(tem.at(i)))
{
cout<<"nope.jpg"<<endl;
return 0;
}
}
pp.serial11_14=tem;
return pp.serial11_14;
}
}
int setyear8(int tem)
{
printype pp;
if(tem>99||tem<0)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.year8=tem;
return pp.year8;
}
}
int setmonth7(int tem)
{
printype pp;
if(tem>12||tem<1)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.month7=tem;
return pp.month7;
}
}
int setday6(int tem)
{
printype pp;
if(tem>31||tem<1)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.day6=tem;
return pp.day6;
}
}int sethour5(int tem)
{
printype pp;
if(tem>23||tem<0)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.hour5=tem;
return pp.hour5;
}
}
int setminute2(int tem)
{
printype pp;
if(tem>59||tem<0)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.minute2=tem;
return pp.minute2;
}
}
void setup(char tem[8][15])
{
for (int x=0;x<8;x++)// set to all blanks
{
for (int y=0;y<15;y++)
{
tem[x][y]=' ';
}
}
}
void darray(char tem[8][15])
{
for (int x=0;x<8;x++)// set to all blanks
{
cout <<"\t-------------------------------"<<endl;
cout <<"\t|";
for (int y=0;y<15;y++)
{
cout << tem[x][y];
cout<<"|";
}
cout <<"\n";
}
cout <<"\t-------------------------------"<<endl;
}
void dpinfo(printype mc)
{
cout <<"The unknown is:\t"<<mc.unknown15<<"\nThe String is:\t"<<mc.serial11_14<<"\n Time:\n\n Year: 20"<<mc.year8<<" month: "<<mc.month7<<"\n day: "<<mc.day6<<" hour: "<<mc.hour5<<"\n minute: "<<mc.minute2<<endl;
}
void spar(char tem[8][15])
{
int count=0;
for (int x=0;x<7;x++)
{
for (int y=0;y<15;y++)
{
if(tem[x][y]=='*')
{
count+=1;
}
}
if(count%2==0)
{
tem[x][0]='*';
}
}
count=0;
for (int a=0;a<7;a++)
{
for (int z=0;z<7;z++)
{
}
}
}
void ftarray(printype &pt)
{
int tem=0;
for (int x=1;x<15;x++)
{
switch(x)
{
case 1:
{
tem=pt.minute2;
break;
}
case 4:
{
tem=pt.hour5;
break;
}
case 5:
{
tem=pt.day6;
break;
}
case 6:
{
tem=pt.month7;
break;
}
case 7:
{
tem=pt.year8;
break;
}
case 9:
{
for (int j = 1; j < 8; j++)
{
pt.dots[j][x] = '*';
}
}
case 10:
{
tem=atoi(pt.serial11_14.substr(6,2).c_str());
break;
}
case 11:
{
tem=atoi(pt.serial11_14.substr(4,2).c_str());
break;
}
case 12:
{
tem=atoi(pt.serial11_14.substr(2,2).c_str());
break;
}
case 13:
{
tem=atoi(pt.serial11_14.substr(0,2).c_str());
break;
}
case 14:
{
tem=pt.unknown15;
break;
}
}
if(x==1||x==4||x==5||x==6||x==7||x==10||x==11||x==12||x==13||x==14)
{
if (tem>=64)
{
pt.dots[1][x]='*';
tem-=64;
}
if (tem>=32)
{
pt.dots[2][x]='*';
tem-=32;
}
if (tem>=16)
{
pt.dots[3][x]='*';
tem-=16;
}
if (tem>=8)
{
pt.dots[4][x]='*';
tem-=8;
}
if (tem>=4)
{
pt.dots[5][x]='*';
tem-=4;
}
if (tem>=2)
{
pt.dots[6][x]='*';
tem-=2;
}
if (tem>=1)
{
pt.dots[7][x]='*';
tem-=1;
}
}
}
}
In C++, struct and class is the same thing, other than the default access level. All you need to do is replace
struct printype
{
//...
};
with
class printype
{
public:
//...
};
You can also probably replace the functions that take a printype as argument by value with member functions:
void dpinfo(printype);
becomes
class printype
{
public:
//....
void dpinfo();
};
and will operate on this rather than the parameter.
Methods that return an object printype can become constructors.
I suspect however you have several issues with your code:
int getunknown15()
{
printype tem;
cout <<"-----------------------------------------------------"<<endl;
cout <<" Enter the Unkown Variable (0-127): ";
cin >>tem.unknown15;
cout <<"-----------------------------------------------------"<<endl;
return tem.unknown15;
}
Here, for example, you don't need the tem variable... it does nothing. You can directly read an int an return that, tem will be destroyed on function exit anyway.
Maybe you're looking for a member function, for example:
int printype::setyear8(int tem)
{
if(tem>99||tem<0)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
this->year8=tem;
return this->year8;
}
}
This way the object is modified and you don't lose changes. However, your coding style suggests little to no knowledge of oop. I suggest reading a good book before continuing, as I doubt that, as it is, the answer will make much sense to you.
First of all, a struct and a class are the same in C++, only difference is that a struct is default public and a class is default private. All you do is change struct to class
Looking at your code, however, I'm assuming you are converting from C to C++ and want to add your functions as methods to the class. To do this, you simply add the prototypes to the class declaration and then add the class space to the function implementations. You should also add any relevant constructors and a destructor in necessary
In a h file
class Printype {
char **dots;
int unknown15; // can have values of 0..127
string serial11_14; // 8 characters 00000000...99999999
int year8; // without century, 0..99
int month7; // 1..12
int day6; // 1..31
int hour5; // 0..23
int minute2; // 0..59
//Constructors
Printype(); //Default
Printype(const Printype &cpy); //Copy
Printype(int yr, int mo, int d, int hr, int min); //Sample initializer
//Destrutor
~Printype();
//Methods (only gonna do 2 for example)
int getYear();
void setYear(int y);
};
In a cpp or cc file
#include "printype.h"
Printype::Printype() {
dots = new char*[8];
for(int i=0;i<8;++i) {
dots[i] = new char[15];
}
unknown15 = 0; serial11_14 = ""; year8 = 0;
month7 = 0; day6 = 0; hour5 = 0;minute2 = 0;
}
Printype::Printype(const Printype &cpy) {
//Deep copy all values from cpy to this
}
Printype::Printype() {
dots = new char*[8];
for(int i=0;i<8;++i) {
dots[i] = new char[15];
}
unknown15 = 0; serial11_14 = ""; year8 = yr;
month7 = mo; day6 = d; hour5 = hr;minute2 = min;
}
//Destructor (free allocated memory)
Printype::~Printype() {
for(int i=0;i<8;++i) {
delete[] dots[i]; dots[i] = NULL;
}
delete[] dots; dots = NULL;
}
//Methods
int Printype::getYear() {
return year8;
}
void Printype::setYear(int y) {
year8 = y;
}
You should also implement an = operator. Hope this gets you started and answers your question though. You should really read up on some general OOP in addition to C++ syntax, patterns, etc. A lot of this will likely look foreign and not make much sense, and it will take to long to explain in this forum. There are tons of resources online regarding this material so you should try to read up on it.