13

I am in Visual Studio and am getting 'ifstream undeclared identifier' with this code (same for ofstream)

#include <iostream>
#include <iomanip>
#include <fstream>
void main()
{
    ifstream infile("file.txt");
    ofstream outfile("out.txt");
}

do I need to include something else?

peterh
  • 11,875
  • 18
  • 85
  • 108
rach
  • 701
  • 6
  • 16
  • 20
  • 4
    [The correct return type for `main` is `int`.](http://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main/4207223#4207223) – James McNellis May 09 '11 at 02:43

3 Answers3

45

You need to scope it. Use using namespace std; or preface ifstream and ostream with std::

For example, std::ifstream

Currently, the compiler does not know where these structures are defined (since they are declared/defined within the std namespace). This is why you need to scope your structures/functions in this case.

RageD
  • 6,693
  • 4
  • 30
  • 37
6

You need to reference the standard namespace (std). Try this:

#include <iostream>
#include <iomanip>
#include <fstream>
void main()
{
    std::ifstream infile("file.txt");
    std::ofstream outfile("out.txt");
}
jwismar
  • 12,164
  • 3
  • 32
  • 44
1

You can use

using namespace std;

instead of prefixing everyline with std::

Bronumski
  • 14,009
  • 6
  • 49
  • 77
  • 1
    Always pay attention to hint people to where exactly they can use "using namespace". It's alright inside your .cpp source, but could be horrible in the header. – Cadoiz Apr 15 '19 at 23:06