tags:

views:

63

answers:

3

I am trying to print into a file in C++ and for some reason I keep getting this weird error:

error C2061: syntax error : identifier 'ofstream'

I included the following:

#include <fstream>
#include <iostream>

This is my function:

void Date::PrintDate(ofstream& resultFile) const
{
    resultFile << m_day << "/" << m_month << "/" << m_year;
}

I am using namespace std.


I figured it out, it was all because I did not include the file in the right way.

+3  A: 

Use std::ofstream

This is because we have to explicitly specify which ofstream we are talking about. Since the standard namespace std contains the name ofstream, it has to be explicitly told to the compiler

There are essentially two ways:

Just before all the include files in the .cpp file, have a using directive

1: using namespace std;

or

2: prefix each name from the namespace std with std::

EDIT 2:

Your revised function declaration should look as follows as Option 1 (from above) is a preferred way to avoid global namespace pollution usually

void Date::PrintDate(std::ofstream& resultFile) const 
{ 
    resultFile << m_day << "/" << m_month << "/" << m_year; 
} 
Chubsdad
void Date::PrintDate(std::ofstream after the includes (and look up namespaces)
DyP
@Nadav: You can either add a `using namespace std;` right after the `#include` or use the fully qualified name `std::ofstream` every time you use `ofstream`.
casablanca
i already am using std namespace and seems like this is not my problem
Nadav Stern
Naveen
@Nadav Stern: Another unrelated comment is to have error/exception handling while dealing with I/O operations
Chubsdad
for some reason after using std:: i am getting this error:error C2039: 'ofstream' : is not a member of 'std'
Nadav Stern
this is strange. ofstream should be provided when including <fstream>, and is placed in the std namespace. try either basic_ofstream<char, char_traits<char> > or give us a complete file.
DyP
A: 

Thinking I was going insane, I tried compiling a modified/simplified version, and it works fine. Are you sure you're using a C++ compiler and not a C compiler? e.g. g++ instead of gcc.

#include <iostream>
#include <fstream>

using namespace std;

void printDate(ofstream& resultFile)
{
resultFile << 1 << "/" << 1 << "/" << 2010;
}

int main(int arg, char **argv)
{
ofstream ofs("ADate.txt");
if (!ofs) cerr << "huh?";
printDate(ofs);
}
paul
i am using visual studio 10 proffesional version and i am using cpp files ofc
Nadav Stern
A: 

the problem was with the order of the included "h" files i didnt include in the right order after fixing it all worked perfectly.

Nadav Stern
@Nadav Stern: Can you please let us know what exactly it was? What was the old order and what was the new order?
Chubsdad