Hi I'm a c++ beginner and this is one of my assignments and I'm a bit stuck. This isn't my entire code it's just a snippet of what I need help with. What I'm trying to do is have one function dedicated to exporting everything with that function into a text file which is called results.txt. So the line "does this work" should show up when I open the file, but when I run the file I get errors like
"Error C2065: 'out' : undeclared identifier"
"Error C2275: 'std::ofstream' : illegal use of this type as an expression"
"IntelliSense: type name is not allowed"
"IntelliSense: identifier "out" is undefined"
#include
#include
#include
using namespace std;
//prototypes
void output(ofstream& out);
int main()
{
output(ofstream& out);
ifstream in;
in.open("inven.txt");
ofstream out;
out.open("results.txt");
return 0;
}
void output(ofstream& out)
{
out << "does this work?" << endl;
}
Right now it's really late and I'm just blanking out on what I'm doing wrong.
解决方案
First of all, this is fine:
void output(ofstream& out)
{
out << "does this work?" << endl;
}
However, this is not:
int main()
{
output(ofstream& out); // what is out?
ifstream in;
in.open("inven.txt");
ofstream out;
out.open("results.txt");
return 0;
}
This is the first error you get: "Error C2065: 'out' : undeclared identifier", because the compiler doesn't know about out yet.
In the second fragment you want to call output with a specific ostream&. Instead of calling a function, you're giving a function declaration, which isn't allowed in this context. You have to call it with the given ostream&:
int main()
{
ifstream in;
in.open("inven.txt");
ofstream out;
out.open("results.txt");
output(out); // note the missing ostream&
return 0;
}
In this case you call output with out as parameter.