Help

This is a discussion on Help within the C++ Programming forums, part of the General Programming Boards category; I've written my code for my homework, but when I execute it, rather than displaying the content of the file, ...

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    10

    Help

    I've written my code for my homework, but when I execute it, rather than displaying the content of the file, it gets erased.

    I can't figure out what I'm doing wrong.

    Here's what I've written.

    Code:
    
    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    
    using namespace std;
    
    int main ()
    {
        char next, advice;
        
        ifstream fin;
        ofstream fout;
        
        fin.open ("F:\\CS 2\\advice.txt");
        fout.open ("F:\\CS 2\\advice.txt");
        
        if (fin.fail())
        {
           cout << "File failed to open.\n";
           system ("pause");
           exit (1);
        }
        
        if (fout.fail())
        {
           cout << "File failed to open.\n";
           system ("pause");
           exit (1);  
        }      
        
        
        while (fin >> next)
        {
        fin.get(next);
        cout << next;
        }
        
        cout << "\n\n" << "Input your own advice.\n";
        cin >> advice;
        
        while (! cin >> '\n')
        {
        cin.get(advice);
        fout << advice;
        }
        
        fin.close ( );
        fout.close ( );
        system ("pause>nul");
    }

  2. #2
    Registered User
    Join Date
    Sep 2008
    Posts
    48
    you need to open the fout stream in append mode
    Code:
     ofstream fout("F:\\CS 2\\advice.txt", ios:: app);

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,821
    You're using the same file for input and output.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21