-2

I am working with fstream within C++, and it works just fine through the main() function. When I tried to use the Header File, and the same simple program, it does not work. I think I need to use the reference variable parameter in the Header File, but I am just not sure how to write the code. Can I write it so that the main function will go to the Header File to get data?

Main Function

#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>

#include "Prog_5_15.h"

using namespace std;

int main()
{
    cout << "Hi Reed";
    //I would like to try to keep the data in 
    //the Header File

    //This works right
    ofstream outputFile;
    outputFile.open("e:\demofile2.txt");

    cout << "Now writing data to the file\n";
    outputFile << "Bach\n";
    outputFile << "Beethoven\n";
    outputFile << "Mozart\n";
    outputFile << "Schubert\n";

    outputFile.close();

    // Can I put a function here from the Header File
    // that gets info from fstream? 
    // Write_This();  ??
    cin.get();

    return 0;
}

Header File

#pragma once

#ifndef P515_h
#define P515_h


class Prog_5_15
{
public:
    Prog_5_15();
    ofstream outputFile2;
    outputFile2.open("e:\demoFile3.txt");
    outputFile2.close();
    void Write_This();    // This part needs do be re-written
    ~Prog_5_15();
};

#endif // !P515_h
#include <iostream>
#include "Prog_5_15.h"

using namespace std;

Prog_5_15::Prog_5_15()
{
}

void Prog_5_15::Write_This()  // This needs to be re-written I think
{
    cout << "Now writing data to the file\n";
    outputFile << "Bach\n";
    outputFile << "Beethoven\n";
    outputFile << "Mozart\n";
    outputFile << "Schubert\n";
}

Prog_5_15::~Prog_5_15()
{
}
O'Neil
  • 3,790
  • 4
  • 16
  • 30
Reed
  • 5
  • 6

1 Answers1

0

Use the same name in your class.

class Prog_5_15
{
public:
    Prog_5_15();
    ofstream outputFile2;
    ...

void Prog_5_15::Write_This()
{
    cout << "Now writing data to the file\n";
    outputFile << "Bach\n";
    ...

You can't have outputFile and outputFile2. Pick one name and stick to it.

Use the constructor to open the file

Prog_5_15::Prog_5_15()
{
    outputFile.open("e:\\demoFile3.txt");
}

Also note that "e:\demoFile3.txt" is wrong, if you want a backslash in a string you have to use \\.

Remove the destructor and the file close statement they are not needed. If your professor tells you different they don't know what they are talking about.

Try that, come back when you have some more questions. And read a book on C++, this is basic stuff and will be covered by any book.

john
  • 85,011
  • 4
  • 57
  • 81