C ++ fstream - 文本文件中的最后一个单词输出单词' s的最后一个字符两次

时间:2014-11-19 20:55:29

标签: c++ string fstream

我正在编写一个打开文本文件(advice.txt)的程序,输出文件中的单词,询问用户的建议输入,并用新建议覆盖旧建议。但是,文本文件的最后一个字的最后一个字符输出两次。

而不是显示

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

该程序将显示此

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

有谁知道如何解决这个错误?

我的程序代码:

//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的内容:

Make a flowchart before you start writing your own program

0 个答案:

没有答案