Error overloading >> Operator reading from file into class - c++

I am currently working on a program for class that requires me to overload the stream extraction operator, >>, to take data from a file straight into a class. I am getting a:
error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::ifstream' (or there is no acceptable conversion)
Here is the specific code the error is affecting.
int main()
#include <iostream>
#include <fstream>
#include <iomanip>
#include "stockType.h"
#include "stockListType.h"
using namespace std;
stockType myStock;
stockListType stockList;
ifstream infile;
infile.open("StockData.txt");
infile >> myStock;
stockType.h Header File
#ifndef STOCKTYPE_H
#define STOCKTYPE_H
#include <string>
#include <fstream>
#include <iostream>
class stockType
{
public:
stockType();
void printStock();
void calcPercent();
char Symbol[3];
float openingPrice;
float closingPrice;
float todayHigh;
float todayLow;
float prevClose;
int volume;
float percent;
friend std::ifstream &operator >> (std::ifstream &in, const stockType &myStock);
};
#endif
stockType.cpp Resource File
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include "stockType.h"
std::ifstream& operator>> (std::ifstream &in, const stockType &myStock)
{
in >> myStock.Symbol;
in >> myStock.openingPrice;
in >> myStock.closingPrice;
in >> myStock.todayHigh;
in >> myStock.todayLow;
in >> myStock.prevClose;
in >> myStock.volume;
return in;
}
most of the searching I have done is people having problems using ostream to do this and are getting their data during program use. Trying to erorr-correct using the ifstream and reading straight from a txt file has been difficult. I can provide whatever additional information is needed. Any help is much appreciated. thanks.

Your input operator signature
std::ifstream& operator>> (std::ifstream &in, const stockType &myStock);
// ^^^^^
makes no sense. To input anything from the stream to the myStock parameter, it has to be non const of course. Also you usually don't want to overload specific implementations of std::istream, thus your signature should look like this:
std::istream& operator>> (std::istream &in, stockType &myStock);

Related

keep getting the error ' no match for 'operator>>' ;

I have seen numerous other questions with the same error but those are from people who haven't overloaded the >> operator. I am having this issue with a few other programs I have written all very similar to each other as they are practice questions.
I have also looked into my textbook and compared my program with their example programs and can't see where I'm going wrong.
The full error is (in main.cpp)
line 17: error: no match for 'operator>>' (operand types are 'std::ifstream {aka std::basic_ifstream}' and 'Suitcase()')|
Any and all advice is greatly appreciated.
My Header is
//suitcase.h
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#ifndef SUITCASE_H
#define SUITCASE_H
using namespace std;
class Suitcase
{
public:
Suitcase();
Suitcase(double p,double w,double v,string s,string b);
~Suitcase();
double calc_ratio();
friend bool operator>(const Suitcase s1,const Suitcase s2);
friend ostream& operator<<(ostream & out,const Suitcase& s);
friend istream& operator >>(istream& in,Suitcase& s);
private:
double price,weight,volume;
string brand,shop;
};
#endif // SUITCASE_H
My implementation is
//suitcaseimplement.cpp
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include "suitcase.h"
using namespace std;
Suitcase::Suitcase()
{
price=0;
weight=0;
volume=0;
shop="";
brand="";
}
Suitcase::Suitcase(double p,double w,double v,string s,string b)
{
price=p;
weight=w;
volume=v;
shop=s;
brand=b;
}
Suitcase::~Suitcase()
{
}
double Suitcase::calc_ratio()
{
return (volume/weight);
}
bool operator>(Suitcase s1,Suitcase s2)
{
if(s1.calc_ratio()>s2.calc_ratio())
return true;
}
ostream& operator<<(ostream & out,const Suitcase& s)
{
out<<"The suitcase with the highest ratio is the "<<s.brand<<endl;
out<<"It is available at "<<s.shop<<endl;
out<<"It weighs "<<s.weight<<"kgs, has a volume of "<<s.volume<<"and costs R"<<s.price<<endl;
return out;
}
istream& operator >>(istream& in,Suitcase& s)
{
in>>s.price>>s.weight>>s.volume>>s.brand>>s.shop;
return in;
}
and finally my main program is.
//main.cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include "suitcase.h"
using namespace std;
int main()
{
ifstream infile;
infile.open("Suitcase.txt");
if(infile.fail())
exit(1);
Suitcase current_suitcase(), best_suitcase();
infile>>best_suitcase;
while(infile>>current_suitcase)
{
if(current_suitcase>best_suitcase)
{
current_suitcase=best_suitcase;
}
}
infile.close();
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout<<best_suitcase;
return 0;
}
This line
Suitcase current_suitcase(), best_suitcase();
declares two functions that return Suitcase instead of defining two variables. This is called the Most vexing parse rule. Removing the superfluous parentheses solves the problem:
Suitcase current_suitcase, best_suitcase;
Also, don't do using namespace std.
In C++ when you have to initialize object without parameters, you must not put the () because it could be parsed as an object definition with an empty initializer or a function declaration the language standard specifies that the ambiguity is always resolved in favour of the function declaration. so instead of
Suitcase current_suitcase(), best_suitcase();
use
Suitcase current_suitcase, best_suitcase;
Note: empty initializer can be called with curly brackets in this way Suitcase current_suitcase{};
Also, just in case:
note that bool operator>(const Suitcase s1,const Suitcase s2); the const qualifier on the params is applied to an object, and those objects are been created by the copy constructor, so the const qualifier is useless in this case, but instead of taken out the const to the params, change those params to alias of objects, so declare the operator in this way bool operator>(const Suitcase& s1,const Suitcase& s2);
if you want to explicit an empty destructor use this sintax Suitcase::~Suitcase() = default; but take in account that C++ has already a default destructor that will do the same thing of an empty destructor like your
it's not a good trend using using namespace std;: instead just declare the function you want to use of that namespace, like so using std::cout; using std::cin;

C++ overloading the ostream and istream operators

The aim of this code is to read the file containing the name, dollars in billions and the country which are separated by tabs.
I need to create a class Billionaire and overload the ostream and istream operators to conveniently
read the file into a vector and write the content to the output. And then create a map which maps the country string to a pair. The pair contains a copy of the first
billionaire of every country from the list and a counter to count the number of billionaires per
country. However, I cannot overload stream and stream operators.
I've tried to overload these operators in Billionaire class but I am ending up with errors.
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <set>
#include <map>
#include <string>
#include <iterator>
#include <fstream>
#include <istream>
#include <ostream>
using namespace std;
class Billionaire{
//overload the ostream and istream operators to conveniently
//read the file into a vector and write the content to the output
public :
friend ostream &operator<<(ostream &stream, Billionaire o);
friend istream &operator>>(istream &stream, Billionaire &o);
};
int main(){
std::ifstream stream("Forbes2018.txt");
if(!stream){
cout << " WARNING : File not found !" << endl ;
}
vector <Billionaire> billionaires;
copy (istream_iterator<Billionaire>( stream ),
istream_iterator<Billionaire>() , back_inserter( billionaires ));
copy (billionaires.begin () , billionaires.end () ,
ostream_iterator < Billionaire >( cout , "\n"));
map < string , pair < const Billionaire , size_t >> m;
}
I am having 2 errors:
:-1: error: symbol(s) not found for architecture x86_64
:-1: error: linker command failed with exit code 1 (use -v to see invocation)
Your overload attempt is a good start: you have announced to the compiler that there will be an overload:
friend ostream &operator<<(ostream &stream, Billionaire o);
friend istream &operator>>(istream &stream, Billionaire &o);
Unfortunately, something is missing. This is what the linker message says. You still need to tell the compiler how this overload looks like:
ostream &operator<<(ostream &stream, Billionaire o) {
// put your code here
...
return stream;
}
istream &operator>>(istream &stream, Billionaire &o) {
// put your code here
...
return stream;
}
In case you have defined these operators in the Billionaire, the compiler wont be able to use them here : in main you invoke the free standing operator (that you have declared as friend), whereas you would have defined class members that have to be invoked on a Billionaire with the . or -> operator and have a different signature than what you’re using in main.

overloading istream operator >> with getline gives error

I really don't know why, but I'm struggling with my >> operator getting it to work properly with getline.
Basically, I have a command class in which I want to assign the user input to its chain attribute and after that I want to split user input with space as delimiter to its string array param
For now, I just want to get the first one to work correctly, for the split, I'll do it later with strok.
Edit:
My error:
Commande.cpp: In function 'std::istream& operator>>(std::istream&, Commande&)':
Commande.cpp:82:39: error: no matching function for call to 'std::basic_istream<char>::getline(std::__cxx11::string&, int)'
stream.getline(commande.chaine, 256);
Command.cpp
Command::Command() {
}
Command::Command(std::string _chain) {
chaine = _chain;
}
Command::Command(const Command& orig) {
}
Command::~Command() {
}
std::istream& operator >> (std::istream &stream, Command& command)
{
stream.getline(command.chain, 256);
return stream;
}
Command.h
#ifndef COMMAND_H
#define COMMAND_H
#include <iostream>
#include <assert.h>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include "Command.h"
public:
std::string chain;
std::string param[10];
Command();
Command(std::string _chain);
Command(const Command& orig);
virtual ~Command();
private:
friend std::istream& operator >> (std::istream&, Command&);
};
#endif /* COMMAND_H */
Main.cpp
include "command.h"
int main(int argc, char** argv) {
Command command;
std::cin >> command;
}
I changed my fonction as #Thomas Mattews recommanded and it works perfectly. thumbs up for all the other answers too.
std::istream& operator >> (std::istream &stream, Command& command)
{
std::getline(stream, command.chain);
return stream;
}

Why I cannot connect my source file to the header file?

I tried to make a header called Paitent_info.h as you can see here :
#ifdef GUARD_Paitent_info
#define GUARD_Paitent_info
#include <iostream>
#include <string>
#include <vector>
struct Paitent_info {
std::string name;
std::vector<double> tem;
};
bool compare(const Paitent_info&, const Paitent_info&);
std::istream& read(std::istream&, Paitent_info&);
std::istream& read_tem(std::istream&, std::vector<double>&);
#endif
and here is Paitent_info.cpp :
#include "Paitent_info.h"
using std::istream; using std::vector;
bool compare(const Paitent_info& x, const Paitent_info& y)
{
return x.name < y.name;
}
istream& read(istream& ip, Paitent_info& p)
{ // do something
return ip;
}
istream& read_tem(istream& in, vector<double>& tem)
{ // do something
return in;
}
I got many error messages from this code :
std::istream and std::vector has not been declared
Paitent_info does not name a type.
request for member ‘name’ in ‘x’ and 'y', which is of non-class type ‘const int’.
istream does not name a type.
I do not know why I got all these error messages, please help me.
You got a typo in the header guard:
#ifdef GUARD_Paitent_info
should be
#ifndef GUARD_Paitent_info
Currently the guard causes the header to be included only if it already has been included. Think about that for a second ;).

why am I getting an error when I pass an ifstream&?

I'm trying to code a simple program that uses an ifstream and scanner to read a text file. For some reason I'm getting this error: "In passing argument 1 of 'bool ReadVector(std::ifstream&, Vector<double>&)'". Any idea what I've done wrong?
#include <iostream>
#include <fstream>
#include <string>
#include "scanner.h"
#include "genlib.h"
#include "simpio.h"
#include "vector.h"
// prototype
bool ReadVector(ifstream & infile, Vector<double> & vec);
// main
int main(){
Vector<double> vec;
ifstream infile;
infile.open("SquareAndCubeRoots.txt");
if (infile.fail()) Error("Opening file screwed up");
bool foo = ReadVector(&infile, &vec); // stub
cout << foo;
infile.close();
return 0;
}
// stub
bool ReadVector(ifstream & infile, Vector<double> & vec){
return true;
}
ReadVector accepts a reference, but you are giving a pointer. Just call
bool foo = ReadVector(infile, vec);
You're trying to pass a pointer, while the argument is a reference. Remove address-of operators (ReadVector(infile, vec)).