0

I am writing a program that opens a text file (advice.txt), outputs the words in the file, asks for advice input from the user, and overwrites the old advice with the new advice. However, the last character from the text file's last word are outputted twice.

Instead of displaying

"Make a flowchart before you start writing your own program"

The program would displaying this instead

"Make a flowchart before you start writing your own programm"

Does anyone know how to fix that bug?

My program code:

//Written by: Edward Santiago
//Assignment: Lab9_m.cpp
//Class: CO SCI 243
//Date: November 19, 2014
//Description: A program that outputs the current advice on advice.txt and replaces it with the user's inputs
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
    char symbol;
    ifstream in_stream;
    ofstream out_stream;
    in_stream.open("advice.txt");//opens the text file
    if (in_stream.fail())
    {
        cout << "File not found" << endl;//if the file cannot be found
        exit(1);
    }
    string message;//declaring the user's input
    cout << "Advice from advice.txt: \n";
    cout << "\n";
    while(!(in_stream.eof()))//this while loop outputs every character in the file
    {
        in_stream.get(symbol);
        cout<<symbol;
    }
    cout << "\n";
    cout << endl;
    cout << "Write your own piece of programming advice:" << endl;
    getline(cin,message);//grabs input from the user
    ofstream outFile;
    outFile.open("advice.txt");//saves information to advice.txt
    outFile << message;
    cout << "Thank you for the message. The next person who \n";
    cout << " opens this program will be able to read it.";
    in_stream.close();
    out_stream.close();
    return 0;
}

advice.txt's contents:

Make a flowchart before you start writing your own program
  • 1
    `while(!(in_stream.eof()))` is probably wrong! – πάντα ῥεῖ Nov 19 '14 at 20:57
  • http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong third time in 10 minutes – Neil Kirk Nov 19 '14 at 20:57
  • @NeilKirk Yes, it's a very frequent misconception :-P ... – πάντα ῥεῖ Nov 19 '14 at 20:58
  • @NeilKirk _"Don't people read a tutorial before they start programming these days?"_ That good old tradition, seems to loose significance nowadays. But don't worry, it could be a seasonal phenomenon, it's autumn, and a lot of new students assigned to the courses now. (should I say _assigned to the curses_ rather?) – πάντα ῥεῖ Nov 19 '14 at 21:05

0 Answers0