Reputation: 31
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 <iostream>
#include <string>
#include <fstream>
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.
Upvotes: 3
Views: 17130
Reputation: 503
Since you described yourself as a begginer, I'll answer accordingly and hopefully in a educational manner. Here is what is happening: Think of fstream
, ofstream
and ifstream
as smart variable types (even if you know what classes are, think like that for the sake of logical clarity). Like any other variable, you have to declare it before you use. After it is declared, that variable can hold a compatible value. The fstream
variable types is for holding files. All variations of it hold the same thing, just what they do that is different.
You use the variable to open a file, use it in your program, then close.
Hope this helps
Upvotes: 2
Reputation: 105886
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.
Upvotes: 8