我省略了很多代码和大部分原始输入文件,只是为了让阅读更容易,更简单,并专注于一个特定的问题。
每次我尝试编译此代码时:
#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;
}
这是输入文件:
2.0 + 2.0
我总是得到错误
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>}'|
我不确定我做错了什么。经过无数个小时的研究,我已经在这里工作了几个小时,仍然没有找到解决方案。我对cpp很新,只有其他语言的经验,这就是为什么我正在努力学习一个基本的概念。非常感谢任何帮助。
答案 0 :(得分:0)
您似乎有关于流的混合信息。您在ifstream
中正确创建了一个main()
对象,该对象将绑定到文件,但是您的函数签名:
void readExpression(ostream &fin, double operand1, char oepratr, double operand2);
使用std::ostream&
- 输出流,而不是输入流。 std::ifstream
继承自std::istream
,用于从读取,而不是写入。您想要做的是将其更改为:
void readExpression(istream &fin, double operand1, char oepratr, double operand2);
除此之外,你的函数体也是不正确的。您不使用参数fin
,但总是从std::cin
读取。因此,您需要将cin >> ...
更改为fin >> ...
。您的完整功能如下:
void readExpression(istream &fin, double operand1, char operatr, double operand2)
{
fin >> operand1 >> operatr >> operand2;
}
您可能有兴趣阅读this question and answers to it。