Ifstream using Class private variables
Feb 8, 2018 at 1:47am UTC
So I am trying to read in a file using private class variables. There might be another way to do this, but this is what I could think of. Note, its my first project using classes and private and public members. Was I on the right path atleast? I keep getting an error for the int main function. How can I fix it?
This is my main:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include "Record.h"
#include <sstream>
int main ()
{
Record employee;
ifstream myFile;
myFile.open("Project 3.dat" );
string str;
int i=0;
if (myFile.is_open())
{
while (getline(myFile, str))
{
istringstream ss(str);
ss >> employee.set_name(str) >>
employee.set_id(stoi(str)) >> employee.set_rate(stoi(str)) >>
employee.set_hoursWorked(str);
}
}
return 0;
}
This is my header file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Record
{
private :
string name;
int id;
double rate;
double hours;
public :
Record();
Record (string n, int empid, double hourlyRate, double hoursWorked); // constructor
void read_data_from_file();
double calculate_wage();
void print_data();
/* ASETTERS AND GETTERS */
void set_name (string n);
string get_name();
void set_id (int empid);
int get_id();
void set_rate (double hourlyRate);
double get_rate();
void set_hoursWorked(double hoursWorked);
double get_hoursWorked();
/* END OF SETTERS AND GETTERS */
};
THis is my .cpp file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include "Record.h"
Record::Record():name(), id(0), rate(0), hours(0) {} //default constructor must be implemented first
Record::Record(string n, int empid, double hourlyRate, double hoursWorked)
{
name = n;
empid = id;
hourlyRate = rate;
hoursWorked = hours;
}
//
void Record::set_name(string n)
{
name = n;
}
string Record::get_name()
{
return name;
}
//
void Record::set_id(int empid)
{
id = empid;
}
int Record::get_id()
{
return id;
}
//
void Record::set_rate(double hourlyRate)
{
rate = hourlyRate;
}
double Record::get_rate()
{
return rate;
}
//
void Record::set_hoursWorked(double hoursWorked)
{
hours = hoursWorked;
}
double Record::get_hoursWorked()
{
return hours;
}
//
void Record::read_data_from_file()
{
}
double Record::calculate_wage()
{
return (rate * hours);
}
Feb 8, 2018 at 2:01am UTC
also tried
1 2
istringstream ss(str);
ss >> employee.get_name(str) >> employee.get_id(stoi(str)) >> employee.get_rate(stoi(str)) >> employee.get_hoursWorked(stoi(str));
Last edited on Feb 8, 2018 at 2:01am UTC
Topic archived. No new replies allowed.