-1

I cant seem to have output appears in my .txt file. I would like to append below the text file in future.

using namespace std;

int main()
{
    string month;
    int year;
    stringstream filename;

    cin >> month;
    cin >> year;

    filename << "Expenses_" << month << "_" << year << ".txt";
    ofstream myfile(filename.str()); 

    myfile.open(filename.str());
    myfile << "Hello World!";
    myfile.close();

    return 0;
}
Dean Seo
  • 5,486
  • 3
  • 30
  • 49
  • [Any good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) should have information about it. [A good reference of the C++ input/output system](http://en.cppreference.com/w/cpp/io) should also be helpful. – Some programmer dude Nov 17 '17 at 08:01
  • http://www.cplusplus.com/reference/fstream/ofstream/open/ – macroland Nov 17 '17 at 08:03

2 Answers2

0

Open your file as:

std::ofstream myfile(filename.str(), std::ofstream::out | std::ofstream::app);

And passing the filename while creating the object of ofstream will open that file too, you don't need to call .open again.

Ahmad Khan
  • 2,655
  • 19
  • 25
0
ofstream myfile(filename.str(), ofstream::out | ofstream::app);

The constructor automatically opens the file for writing and moves the writing pointer to the end of the file, so you can append to the file. There's no need to open the file again because the std::ofstream(const char*, int) consturctor has already opened the file for you.

The alternative is:

ofstream myfile;
myfile.open(filename.str(), ofstream::out | ofstream::app);
iBug
  • 35,554
  • 7
  • 89
  • 134