-1

I omitted much of my code and much of my original input file just to make it easier and simpler to read, and to focus on one specific problem.

Each time I try and compile this code:

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

void readExpression(ostream &fin, double operand1, char oepratr, double operand2);

int main()
{
    double operand1,
           operand2;

    char operatr;

    ifstream fin;
    fin.open("inp.txt");

    readExpression(fin, operand1, operatr, operand2);

    fin.close();

    return 0;
}

void readExpression(ostream &fin, double operand1, char operatr, double operand2)
{
    cin >> operand1 >> operatr >> operand2;
}

This is the input file:

2.0 + 2.0

I always get the error that I have

error: invalid initialization of reference of type 'std::ostream& {aka std::basic_ostream<char>&}' from expression of type 'std::ifstream {aka std::basic_ifstream<char>}'|

I'm not sure what I'm doing wrong. I've been at this for hours and still haven't found a solution, after countless hours of researching. I am fairly new to cpp and only have experience in other language, which is why I am struggling with what seems like an elementary concept. Any help is greatly appreciated.

O.G.
  • 15
  • 3
  • 1
    `ostream &fin` should be `istream &fin` and the line `cin >> operand1 >> operatr >> operand2;` should be `fin >> operand1 >> operatr >> operand2;` – Fureeish Nov 15 '17 at 02:25
  • I assume you also want to pass your arguments by reference to `readExpression`, otherwise it's sort of pointless as they will not be changed outside the scope of that function, and if that's your intention they should just be local variables. – Retired Ninja Nov 15 '17 at 02:44

1 Answers1

0

You seem to have mixed information about streams. You correctly created an ifstream object in main() that will be binded to a file, but your function signature:

void readExpression(ostream &fin, double operand1, char oepratr, double operand2);

uses std::ostream& - the output stream, not the input stream. std::ifstream inherits from std::istream, which is used for reading from, not writing to. What you want to do, is change it to:

void readExpression(istream &fin, double operand1, char oepratr, double operand2);

Besides that, your function body is also incorrect. You do not use the argument fin, but you are always reading from std::cin. Thus you need to change the cin >> ... to fin >> .... Your complete function would look like:

void readExpression(istream &fin, double operand1, char operatr, double operand2)
{
    fin >> operand1 >> operatr >> operand2;
}

You might be interested in reading this question and answers to it.

Fureeish
  • 12,533
  • 4
  • 32
  • 62