This is my header file. Im trying to overload the istream operator and use ifstream in my main function to read in a text file with structured data (rows and columns). I am getting the error "[Error] no match for 'operator>>' (operand types are 'std::istringstream {aka std::basic_istringstream}' and 'std::string {aka std::basic_string}')
I commented where I am getting the error.
My main function is basically empty so far besides The class and object.
#include <iostream>
#include <fstream>
#include <sstream>
#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();
/* SETTERS 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 */
friend istream& operator >> (istream& is, Record& employee)
{
string line;
getline (is, line);
istringstream iss(line);
iss >> employee.get_name(); // where i get error
}
};
You have to change the get_name() to return a non-const reference, like string& get_name(); to get it working/compile. But will look strange.
What you can do instead is pass the member name directly
iss >> employee.name;
that's what friends do.
And don't forget to return the stream is.
Related
Sorry for this extensive (body)question, but I'm having an issue trying to separate my main() function from my read.cc file.
At first I wrote my main() in my read.cc for it was easier to test and it worked perfectly. Now I'm modularizing my code and using main() in a different file (main.cc), but I get a "Multiple definition error".
//course.h
#ifndef _COURSE_H
#define _COURSE_H
#include "dependencies.h"
class Course{
public:
int id;
std::string id_if;
std::string name;
std::string dayTime;
};
#endif
//read.h
#ifndef _READ_H
#define _READ_H
#include "../Classes/course.h"
#include "../Classes/dependencies.h"
using namespace std;
vector <Course*> course;
void readCourse();
void courseCheck(Grade* a, string* temp);
void dispoCheck(Teacher* teacher, string* temp, int day);
const vector<string> explode(const string& s, const char& c);
#endif
//read.cc
void readCourse(){
Course* inp = new Course();
ifstream file;
file.open("../Data/Cursos.csv");
string temp;
getline(file, temp, '\n');
while(file.good()){
getline(file, temp, ';');
inp->id = stoi(temp);
getline(file, inp->id_if, ';');
getline(file, inp->name, ';');
getline(file, inp->dayTime, '\n');
}
course.push_back(inp);
}
//main.cc
#include "Input/read.h"
int main(){
readCourse();
}
Error:
g++ main.cc Input/read.cc -o exe -lm
/tmp/ccyRgnlM.o:(.data+0x0): multiple definition of `course'
/tmp/ccoTZsnQ.o:(.data+0x0): first defined here
collect2: ld returned 1 exit status
From your code, it's not clear what you are trying to do. Since course is only every used inside the readCourse method, so could be declared locally inside the function.
I'd assume that (not shown) you want to also use it in main.
Since this is C++ (rather than C) then global variables are best avoided. Your course variable should be a static member of a class, possibly the Course class itself (and since it's a list, it's better with a plural name). Also, your readCourse method should be a static member, e.g.
//course.h
class Course{
public:
int id;
std::string id_if;
std::string name;
std::string dayTime;
static std::vector<Course*> courses;
static void readCourse();
};
// course.cc
void Course::readCourse(){
...
}
std::vector<Course*> courses; // Defines you single courses object
then in main() you can access it with:
int main(){
Course::readCourse();
Course::courses[0]->doSomething();
}
}
I need to create an ADT for an assignment. I have my class definition in a header file as follows:
#ifndef PHONECALL_H
#define PHONECALL_H
#include <iostream>
using namespace std;
class PhoneCall
{
public:
PhoneCall();
PhoneCall(string newNumber);
~PhoneCall();
string getNumber()const;
int getLength()const;
float getRate()const;
float calcCharge(); //calcuates total cost of call
friend bool operator==(const PhoneCall & call1, const PhoneCall & call2);
friend istream& operator >>(istream& in, PhoneCall& call);
friend ostream& operator <<(ostream& out, const PhoneCall& call);
private:
string number;
int length;
float rate;
};
All the bodies of the functions are in the implementation file (no errors there)
Then in the main application file, when I call the calcCharge() function, I get:
error: 'calcCharge()' was not declared in this scope
This is the only error I get. Here is the application file code:
#include <iostream>
#include <fstream>
#include "PhoneCall.h"
using namespace std;
int main()
{
string num, cellNum;
int length;
float rate, total;
cout << "Enter a phone number: " << endl;
cin>> num;
PhoneCall theCall(num);
ifstream read;
while (read >> cellNum >> length >> rate)
{
if (cellNum == num)
{
total += calcCharge();
}
}
return 0;
}
I know the code for the main application is incomplete, but due to this error I am not able to test whether the program is doing what I need it to do.
It's a member of the class.
total += theCall.calcCharge();
So I am trying to read in a file using private class variables. I am unsure how to display the file. 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/private 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:
#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.get_name(str) >> employee.get_id(stoi(str)) >>
employee.get_rate(stoi(str)) >> employee.get_hoursWorked(stoi(str));
}
}
return 0;
}
This is my header:
#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
#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;
}
//
double Record::calculate_wage()
{
return (rate * hours);
}
There are some issues with your code that I can see. most of your problems aren't related to your question (I mean using a class or private/public members). you have more basic misunderstandings. So here's some explanation that might help you:
1- Using functions : You have some troubles using your defined functions, A function can have multiple input parameters and one return value. basically it's like this return_type function_name(parameter_type param1, ...). it means that if you call this function you need to pass param1,... and expect your function operation and then have a return value of return_type. You defined some set and get functions. if you want to set something you should call set function and pass your desired value to it and it will copy your value to your defined member data, after that you can call get function to retrieve that value. So when you call get function with parameter it will raise error. Here you want to call set function.
2- Using stoi : As you can see you are getting error on using stoi function too, this is a function for converting string to integer, The thing that you missed here is that this function declared in std namespace. If you want to use it you need to use it like this std::stoi(str). one other thing, using namespace std is a bad practice.
3- Design matters : In OOP design, a class must have a purpose and an actual job to do. It might be an interface to abstract class but a bunch of set and get functions will not fulfill the need to create a class. Here if your class is going to do file operations, it's OK, but as far as you shared your code it's just some set and get functions.
Hey guys I am trying to overload ifstream and ofstream but without any success.
Header File:
#include <iostream>
#include <fstream>
using namespace std;
class Complex
{
private:
double real;
double imaginary;
public:
//constructors
Complex();
Complex(double newreal, double newimaginary);
~Complex();
//setter
void setReal(double newreal);
void setImaginary(double newimaginary);
//getter
double getReal();
double getImaginary();
//print
void print();
//methods
Complex conjugate();
Complex add(Complex c2);
Complex subtraction(Complex c2);
Complex division(Complex c2);
Complex multiplication(Complex c2);
friend ifstream& operator >> (ifstream& in, Complex &c1)
{
in >> c1;
return in;
}
};
Test file:
#include <iostream>
#include <fstream>
#include <string>
#include "Complex2.h"
using namespace std;
int main()
{
Complex c1;
ifstream infile;
infile.open("in1.txt");
cout << "Reading from the file" << endl;
infile >> c1;
// write the data at the screen.
infile.close();
return 0;
}
I didnt think the cpp file was important since the header file includes the ifstream.
Everytime I run this program i get this error:
Reading from the file
Segmentation fault (core dumped)
I dont know how to fix it.
Thank you very much.
friend ifstream& operator >> (ifstream& in, Complex &c1)
{
in >> c1; // This is calling this function infinitely!!
return in;
}
The above code implements the operator>> for the Complex type. However, it is a recursive function with no stopping condition.
You probably should be do something similar to the following. Obviously, I don't know how the class was encoded so this is just for illustration.
friend ifstream& operator >> (ifstream& in, Complex &c1)
{
double real;
in >> real;
c1.setReal(real);
double imaginary;
in >> imaginary;
c1.setImaginary(imaginary);
return in;
}
I overlooked that it's a friend function so this could also work.
friend ifstream& operator >> (ifstream& in, Complex &c1)
{
in >> c1.real;
in >> c1.imaginary;
return in;
}
As mentioned in my comment, and in the other answer the operator>>() overload is just called recursively.
One of the most common approaches to fix that, is to declare a put() function in your Complex class like:
class Complex {
public:
// ...
private:
double real;
double imaginary;
istream& put(std::istream& is) {
is >> real;
is >> imaginary;
return is;
}
};
And let the global overload call that function:
friend ifstream& operator >> (ifstream& in, Complex &c1) {
return c1.put(in);
}
I have to make a program to display the weather in Sheffield since 1930.
I have to use sheffield.data for the record.
I have 3 files. Data.cpp, Data.hpp and analyze.cpp
analyze.cpp:
#include <istream>
#include <fstream>
#include <vector>
#include "data.hpp"
using namespace std;
int main()
{
MonthData data();
vector<MonthData> vectorData;
ifstream file ("sheffield.data");
string line;
int l_num = 0;
if (file.is_open()) {
while (getline(file, line))
if (l_num < 4) {
l_num += 1;
}
else {
file >> data;
vectorData.push_back(data);
}
float MinimumDeg = vectorData[0].getMinimum();
int year = vectorData[0].getYear();
for ( size_t a = 0; a < vectorData.size(); a++)
{
MinimumDeg = vectorData[a].getMinimum();
year = vectorData[a].getYear();
}
cout << "Lowest year and month lowest rainfall: '\n'" << "Min Temp;" << MinimumDeg << "C '\n'" << "Year" << year << endl;
return 0;
}
}
:
data.cpp
#include "data.hpp"
#include <iostream>
using namespace std;
istream& operator >> (istream& in, MonthData& data)
{
in >> data.year >> data.year >> data.temp_maximum >> data.temp_minimum >> data.air_frost >> data.rain >> data.sun;
return in;
}
data.hpp:
#ifndef DATA_HPP
#define DATA_HPP
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
class MonthData
{
friend istream& operator >> (istream&, MonthData&);
public:
//overload constructor
MonthData(double, int, double, double, int, double, double);
//Accessor functions
double getYear() const { return year; } //returns the year
int getMonth() const { return month; } //returns the month
double getMaximum() const { return temp_maximum; } //returns maximum temperature
double getMinimum() const { return temp_minimum; } //returns minimum temperature
int getFrost() const { return air_frost; } //returns air frost
double getRain() const { return rain; } //returns rainfall
double getSun() const { return sun; } //returns no of hours of sunshine
private:
double year;
double month;
double temp_maximum;
double temp_minimum;
int air_frost;
double rain;
double sun;
};
#endif
Why am I getting this error?
[sc14da#cslin035 cw]$ g++ data.cpp data.hpp analyze.cpp -o analyze
analyze.cpp: In function ‘int main()’:
analyze.cpp:11: error: no matching function for call to ‘MonthData::MonthData()’
data.hpp:17: note: candidates are: MonthData::MonthData(double, int, double, double, int, double, double)
data.hpp:12: note: MonthData::MonthData(const MonthData&)
If you do not provide any constructor in your class, the compiler will automatically create one for you.
In your class, you have specified a particular constructor:
MonthData(double, int, double, double, int, double, double);
As soon as you provide any constructor, the compiler will not create a default constructor (i.e. one that takes no parameters).
You are calling
MonthData data();
You are passing no parameters here but you have no constructor that takes no parameters.
You probably meant to call
MonthData data(with 7 parameters);
Alternatively, add the following to your MonthData class body:
MonthData();
Then in your data.cpp, need to provide the code for what this constructor should do, i.e.
MonthData::MonthData()
{
//Initialise as required - but better to use a member initialization list
}
It would be better to use a member initialization list for your 7 member variables.
For example:
MonthData::MonthData()
: year(2014), month(2), temp_maximum(15.4), temp_minimum(2.1), air_frost(5), rain(5.6), sun(7.6) //Use desired default values
{}
This simple constructor code could instead be put directly in the class body in the header file:
class MonthData
{
public:
//overload constructor
MonthData(double y, int m, double max, double min, int fr, double r, double s)
: year(y), month(m), temp_maximum(max), temp_minimum(min), air_frost(fr), rain(r), sun(s) {};
//default constructor
MonthData()
: year(2014), month(2), temp_maximum(15.4), temp_minimum(2.1), air_frost(5), rain(5.6), sun(7.6) {};
etc
};
In addition - review your variable types. Should year really be a double? Also you have month declared as a double but your accessor returns an int.
That's not surprising as you haven't included a default constructor. Or, more specifically, a constructor that matches this line:
MonthData data();
Solution: add a default constructor in your base MonthData class (data.hpp).