Search code examples
c++visual-c++operator-overloadingifstream

Error overloading >> Operator reading from file into class


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.


Solution

  • 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);