I'm trying to create a function below called load() that copies all the records from my graduate.dat file into my vector of Record pointers called primaryCollection. I created a Record class with variables that make up each Record, and in my load() function in createReport.cc I attempted to read each line in the file, create a Record object with each line, and then add it to my vector.
The problem is I keep getting the error:
createReport.cc: In static member function ‘static void createReport::load()’:
createReport.cc:25:71: error: expression list treated as compound expression in initializer [-fpermissive]
Record* record(year, province, degree); //create Record object with this data
^
createReport.cc:25:71: error: invalid conversion from ‘int’ to ‘Record*’ [-fpermissive]
I'm not sure why this is and I would appreciate some help trying to read the file add each record to my collection.
My graduate.dat file is formatted like below in the format < year province degree >
2000 AB Bachelor's
2005 AB Bachelor's
2005 MB College
primaryCollection is required to be a vector of record pointers and I'm also not allowed to use std::map in this task.
Record.h
#ifndef RECORD_H
#define RECORD_H
#include <iostream>
#include <string>
class Record{
public:
Record(int = 0, string = "", string = "");
~Record();
private:
int year;
string province;
string degree;
};
#endif
Record.cc
#include <iostream>
#include <string>
using namespace std;
#include "Record.h"
Record::Record(int i1, string s1, string s2) : year(i1), province(s1), degree(s2){}
Record::~Record(){}
createReport.h
#ifndef CREATEREPORT_H
#define CREATEREPORT_H
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cstdlib>
#include "Record.h"
class createReport{
public:
createReport();
static void load();
protected:
static vector<Record*> primaryCollection; //STL vector of record pointers
};
#endif
createReport.cc
#include <iostream>
using namespace std;
#include <string>
#include "createReport.h"
void createReport::load(){
int year;
string province, degree;
ostream_iterator<Record*> outItr(cout);
ifstream infile("graduate.dat", ios::in);
if (!infile) {
cout << "Error: could not open file" << endl;
exit(1);
}
while (infile >> year >> province >> degree) { //as long as were not at end of file
Record* record(year, province, degree); //create Record object with this data
primaryCollection.push_back(record);
}
cout<<endl<<"List of Records:"<<endl;
copy(primaryCollection.begin(), primaryCollection.end(), outItr); //print records
}
The correct syntax here is:
Record* record = new Record(year, province, degree);
Everything after that is fine, but keep in mind that vector now "owns" the pointers and you're responsible for releasing those allocations somehow. This is where pointer wrappers come in handy.
Related
I'm practicing some basic C++ right now, and decided to create a class in a header file and the constructor, GetString, etc functions in a separate file.
When I create my object using
"Person Bob" and use "." the code works fine, but if I do Person* Bob, the SetName(x) function seg faults, when I use ->SetName(x, with x being a "abc" string or a string variable
Main.cpp
#include <iostream>
#include <string>
#include "namevalue.h"
using namespace std;
int main(){
Person Bob;
string temp = "bob";
Bob.SetName(temp);
Bob.SetMoney(3000);
cout << Bob.GetName() << " " << Bob.GetMoney() << endl;
return 0;
}
Person.h
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
class Person{
public:
Person();
Person(int money, string name);
void SetName(string y);
void SetMoney(int x);
int GetMoney();
string GetName();
private:
int money;
string name;
};
Person.cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <array>
#include "namevalue.h"
using namespace std;
Person::Person(){
name = " ";
money = 0;
}
Person::Person(int x, string y){
SetName(y);
SetMoney(x);
}
void Person::SetMoney(int x){
money = x;
}
void Person::SetName(string x){
name = x;
}
int Person::GetMoney(){
return money;
}
string Person::GetName(){
return name;
}
If you declare a pointer variable, you need to populate it first with a valid instance. Otherwise, it is pointing to invalid memory and you will get the memory fault you are experiencing.
This should work.
Person* Bob = new Person();
Bob->SetName("Bob");
Bob->SetMoney(3000);
When you're finished, free the memory.
delete Bob;
So I am very new to C++ and I am having a hard time learning how too implement classes into a function I have. My prof isn't being helpful in any capacity and I am very lost.
So the jist of the program is to take a file "books.txt" where each line contains an author and a book in the following format: Douglas Adams, The Hitchhiker's Guide to the Galaxy
I am trying to get the function to populate an array with "Book" objects with the title and author data from the file. It takes 4 input arguments: a name of the file as a string, an array of "Book" objects, the number of "Book" objects stored in the array of Book, and the capacity of the library system (with a max of 200).
For each line in the file, I am supposed to instantiate a Book object, fill in the author and title data members (listed in the code below), and append the object to the array of "Book" objects and it will return the numbers of books in the system as an integer.
Here is my header file (Book.h):
#include <iostream>
#include <math.h>
#include <string>
#include <string.h>
#include <fstream>
#include <stdio.h>
#include <cctype>
#include <locale>
#include <algorithm>
using namespace std;
#ifndef BOOK_H
#define BOOK_H
class Book{
private: //Member Variables
string author;
string title;
string inauthor;
string intitle;
string input;
string input2;
public:
Book();
Book(string intitle, string inauthor);
string getTitle();
void setTitle(string input);
string getAuthor();
void setAuthor(string input2);
};
#endif
Here is the .cpp file associated with the header file:
#include <iostream>
#include <math.h>
#include <string>
#include <string.h>
#include <fstream>
#include <stdio.h>
#include <cctype>
#include <locale>
#include <algorithm>
#include "Book.h"
using namespace std;
//Default constructor
Book::Book(){
author = "";
title = "";
}
//Parameterized Constructor
Book::Book(string intitle, string inauthor){
}
//An accessor function that returns the name of the title
string Book::getTitle() {
return title;
}
//A function that assigns the value title to the input given by the user
void Book::setTitle(string title){
title = intitle;
}
//An accessor function that returns the name of the author
string Book::getAuthor() {
return author;
}
//A function that assigns the value author to the input given by the user
void Book::setAuthor(string author){
author = inauthor;
}
And finally, here is the function I am trying to place it into (it is incomplete as every previous attempt I have made to use classes ends in a long list of errors and here is where I can confidently say I can get to):
#include <iostream>
#include <math.h>
#include <string>
#include <string.h>
#include <fstream>
#include <stdio.h>
#include <cctype>
#include <locale>
#include <algorithm>
#include "Book.h"
#include "User.h"
using namespace std;
int readBooks (string filename, int books[] , int bookObj, int capacity){
int i = 0;
ifstream file;
file.open (filename);
if (file.fail()){
return -1;
}
else{
string line;
while ((i < books) && (i < capacity) && (getline(file,line))){
}
}
I bet this is probably a very simple problem but neither the book or any other resources I have been referencing has been able to help me very much. Any help or advice would be greatly appreciated! Thank you!
I can help you out with your class design. It would look something like this:
Book.h
#ifndef BOOK_H
#define BOOK_H
#include <string>
#include <vector>
const int LIBRARY_MAX_CAPACITY = 200;
class Book {
private:
std::string author_;
std::string title_;
public:
Book() : author_( "" ), title_( "" ) {}
Book( const std::string& authorIn, const std::string& titleIn ) :
author_( authorIn ), title_( titleIn )
{}
void setAuthor( const std::string& authorIn ) {
this->author_ = authorIn;
// or just author_ = authorIn;
}
void setTitle( const std::string& titleIn ) {
this->title_ = titleIn;
// or just title_ = titleIn;
}
std::string getAuthor() const { return author_; }
std::string getTitle() const { return title_; }
};
void readBooks( const std::string& filename, std::vector<Book>& books );
#endif // BOOK_H
Book.cpp
#include "Book.h"
#include <fstream>
// this is just pseudo code and will not actually compile
void readBooks( const std::string& filename, std::vector<Book>& books ) {
// open file, test if open correctly
std::ifstream file;
file.open( filename );
// loop through file until end is reached by reading in
// a line of code and getting the contents of the book
while ( file still has data && line <= LIBRARY_MAX_CAPACITY ) {
// get a line of text then parse that line of text.
std::string author = "first string from file before comma"
std::string title = "second string from file after comma"
// create a book object here:
Book book( author, title );
// push back into vector that is passed into this function by reference
books.push_back( book );
}
// done with loop close the file
file.close();
}
Now what ever other function calls this function such as main, or your Library class etc. The std::vector<Book> object will be passed back by reference that is already populated with book objects and std::vector<> has a .size() function that returns it's size as an std::size_t.
I want to fetch value of certain key from back-end.
In back-end the structures are defined and values are initialized.
Consider this as structure defined in back-end:
struct person{
string nme;
string adrs;
int id;
};
person p1 = {"steve","ABC street",23};
The key address corresponds to value of p1.adrs in back-end.
Now the key address is to be mapped to (p1 & adrs) in external file and should get the value "ABC street".
My question is how mapping is to be done for key and its particular structure member in external file and how to fetch value for that key.
Here Can I use std::map concept for this?
I got solution for requirement. But to improve it further, mapping is to be declared in separate file (Here it was declared in .h file)
myfile.h
#ifndef MYFILE_H
#define MYFILE_H
#include <iostream>
#include <algorithm>
#include<vector>
#include <string>
#include <map>
using namespace std;
struct Chassis
{
string InLED;
string AstTg;
};
struct Manager
{
string MngrType;
int count;
};
const Chassis chassis1={"On","null"};
const Manager manager1={"BMC",23};
const map<string, const string>cha1={{"IndicatorLED", chassis1.InLED},{"AssetTag",chassis1.AstTg},{"ManagerType",manager1.MngrType}};
const map<string, int>cha2={{"Count",manager1.count}};
void func(string);
#endif
myfile.cpp
#include <iostream>
#include <string>
#include "myfile.h"
#include <map>
using namespace std;
void func(string item)
{ if(cha1.find(item) == cha1.end()) {if (cha2.find(item) == cha2.end()){} else {cout<< item<<":"<<cha2.at(item)<<endl;} }
else {cout<< item<<":"<<cha1.at(item)<<endl;}
}
main.cpp
#include <iostream>
#include <string>
using namespace std;
#include "myfile.h"
int main() {
string item="IndicatorLED";
func (item);
string item1="AssetTag";
func(item1);
string item2="ManagerType";
func(item2);
string item3="Count";
func(item3);
}
I have tried every combination of #include statements that I can think of, and nothing is working. I am trying to write a basic inheritance program but i keep getting the error error: expected class-name before '}' token and I just do not know what to do about it anymore. I've tried having my main() include the .cpp file of the Executive class, however this error shows up. The program includes 5 types of employees all inherited from the Employee class, and I'm assuming that they are all the same error:
#include <iostream>
#include <string>
#include "Employee.cpp"
#include "Manager.cpp"
#include "Executive.cpp"
#include "Technical.cpp"
#include "Software.cpp"
#include "Test.cpp"
using namespace std;
int main()
{
Employee emp[3];
Executive emp0("John", "Doe", "VP", 100000.0, 1000000.0, 2000.0);
Software emp1("Vincent", "Giuliana", "Project Leader", 150000.0, 200000.0, 1000.0);
Test emp2("Lauren", "Wallis", "Overseer of Testing", 95000, 115000);
emp[0] = emp0;
emp[1] = emp1;
emp[2] = emp2;
for(int i=0; i<3; i++)
emp[i].displayInformation();
emp0.displayInformation();
emp1.displayInformation();
emp2.displayInformation();
return 0;
}
My Employee.h header file is as follows:
#ifndef EMPLOYEE_H_INCLUDED
#define EMPLOYEE_H_INCLUDED
#include <string>
#include <iostream>
using namespace std;
class Employee
{
private:
string fName, lName, jobTitle;
double baseSalary, salary;
public:
Employee();
Employee(string fName, string lName, string jobTitle, double baseSalary);
void calculateSalary(double baseSalary);
void displayName();
void displayBSalary();
void displayJobTitle();
void displayInformation();
...
getters
...
...
setters
...
};
#endif // EMPLOYEE_H_INCLUDED
My Employee.cpp is:
#include <string>
#include <iostream>
#include "Employee.h"
using namespace std;
Employee::Employee()
{
fName = "";
lName = "";
jobTitle = "";
baseSalary = 000000;
}
...
void Employee::setBSalary(double bs) //sets base salary as parameter
{
baseSalary = bs;
}
The top of the Executive.h header class:
#ifndef EXECUTIVE_H_INCLUDED
#define EXECUTIVE_H_INCLUDED
#include <string>
#include <iostream>
//#include "Employee.h"
using namespace std;
class Executive : public Employee
{
private:
string fName, lName, jobTitle;
double baseSalary, salary, bonus, stockOption;
public:
...
};
#endif // Executive_H_INCLUDED
And last but not least, the Executive.cpp file...
#include
#include
#include "Executive.h"
using namespace std;
Executive::Executive()
{
fName = fN;
lName = lN;
jobTitle = jt;
baseSalary = bs;
bonus = b;
stockOption = so;
}
...
void Executive::setSO(double so) //sets stock option as parameter
{
stockOption = so;
}
I think that I have tried to include each header in each file and still, nothing. Any help would be appreciated, and I thank anyone very much in advance!
You must
#include "Employee.h"
in Executive.h, because the compiler must see the declaration of Employee, when a class inherits from it. So, just remove the comments from the #include
I've spent quite a few hours researching and trying to figure out why I'm getting this error. Basically the three files that have to do with the inheriting are CollegeMember.h, Employee.h, and EmpAcademicRecord.h. Employee. is inheriting from CollegeMember.h and EmpAcademicRecord.h is inheriting from Employee.h. Like this CollegeMember <- Employee <- EmpAcademicRecord. The error occurs in EmpAcademicRecord.h. Heres the three files.
CollegeMember.h
#include <cstdlib>
#include <iostream>
#include<ctype.h>
#include<string.h>
#include "Employee.h"
#include "Student.h"
using namespace std;
// ****************************************************************************
// Class Definitions follow
typedef char* String;
// The CollegeMember class
class CollegeMember
{
protected:
int ID_Number;
string FirstName, LastName;
string AddressLine1, AddressLine2, StateProv, Zip;
string Telephone;
string E_Mail;
string answer, answer2, answer3, answer4;//used as sort of booleans for use with validation
// member functions
public:
CollegeMember ( ); // constructor
CollegeMember(const CollegeMember&); //overloaded constructor
void Modify (CollegeMember Member);
void InputData(int x);
string Summary ( ); //summary
string PrintMe(); //fully describes
}; // End of CollegeMember class declaration
Employee.h
#include <cstdlib>
#include <iostream>
#include<ctype.h>
#include<string.h>
#include "EmpAcademicRecord.h"
#include "EmpEmploymentHistory.h"
#include "EmpExtraCurricular.h"
#include "EmpPersonalInfo.h"
#include "EmpPublicationLog.h"
using namespace std;
// ****************************************************************************
// Class Definitions follow
typedef char* String;
// The Employee Class
class Employee: protected CollegeMember
{
float Salary;
protected:
string Department, JobTitle;
// Member Functions
public:
Employee ( ); // constructor
void Modify (Employee ThisEmp);
void InputData(int x);
void SetSalary (float Sal) // Specified as an in-line function
{ Salary = Sal;}
float GetSalary ( ) {return Salary;} // Specified as an in-line function
string Summary ( ); //summary
string PrintMe(); //fully describes
}; // End of Employee class declaration
EmpAcademicRecord.h
#include <iostream>
#include <cstdlib>
#include<ctype.h>
#include<string.h>
using namespace std;
typedef char* String;
class EmpAcademicRecord: protected Employee{ //error occurs on this line
protected:
int ReferenceNumber;
string Institution;
string Award;
string start;
string end;
public:
EmpAcademicRecord();
void InputData (int x);
void Modify(EmpAcademicRecord ThisRec);
void Summary();
};
Any help with this would be greatly appreciated.
That sort of error is usually caused by the type not being defined when you try to use it.
In this case, it appears that you may have included EmpAcademicRecord.h without having first included Employee.h (the includes at the top of the former do not show the latter).
In other words, at the point where the compiler sees:
class EmpAcademicRecord: protected Employee { //error occurs on this line
it has no idea what the Employee class is.
It may be a simple matter of adding:
#include "Employee.h"
to the top of that file, it's a little difficult to be certain since we don't have the code files. In any case, it's certainly a good first step.
Since you have EmpAcademicRecord.h being included by Employee.h, that will probably result in an infinite recursion.
You could fix that with include guards, but I can't see why you need that particulat inclusion. EmpAcademicRecord depends on Employee, not the other way around.