seeming
seeming

Reputation:

Can't create std::ofstream variable despite including <iostream>

I am getting an ofstream error in C++, here is my code

#include <iostream>

int main() {
    std::ofstream myfile;
    myfile.open("example.txt");
    myfile << "Writing this to a file.\n";
    myfile.close();
    return 0;
}

error from Dev-C++ 10

C:\devp\main.cpp aggregate `std::ofstream OutStream' has incomplete type and cannot be defined

Upvotes: 40

Views: 70081

Answers (7)

B_Robinson95
B_Robinson95

Reputation: 11

Add #include <fstream>.

Code:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    std::ofstream myfile;
    myfile.open("example.txt", std::ios::out);
    myfile << "Writing this to a file\n";
    myfile.close();

    return 0;
}

Upvotes: -1

Rohit Chitte
Rohit Chitte

Reputation: 1

I faced the same error because I forgot to use using namespace std; after including it, the problem was solved.

Upvotes: -2

user14148022
user14148022

Reputation:

Include fstream header file that's it. Because ofstream & ifstream are included in fstream.

Upvotes: 0

Sebasti&#225;n Mestre
Sebasti&#225;n Mestre

Reputation: 223

You may not be including the appropiate header file.

adding #include <fstream> at the beggining of your source file should fix the error.

Upvotes: 7

Viet
Viet

Reputation: 18404

You can try this:

#include <fstream>

int main () {
  std::ofstream myfile;

  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();

  return 0;
}

Upvotes: 69

anon
anon

Reputation:

The file streams are actually defined in <fstream>.

Upvotes: 33

1800 INFORMATION
1800 INFORMATION

Reputation: 135255

Probably, you are including the wrong header file. There is a header <iosfwd> that is used for header files that need to reference types from the STL without needing a full declaration of the type. You still are required to include the proper header <iostream> in order to use the types in question.

Upvotes: 2

Related Questions