Search code examples
c++fstream

How Do I Open A txt File Without It Erasing The Previous Content


So I want to be able to open up the file after the console closes and be able to continue adding to the file.

int main(){
    string inputWord;
    ofstream theFile("Info.txt");
    cout << "Type Word or Sentence: ";

    while(getline(cin,inputWord)){
        cout << "Type Word or Sentence: ";
        theFile << "Word or Sentence: " << inputWord;
        theFile << "(Regular Value): " << ch2n(inputWord) << endl;
        theFile << "(Other Value): " << char2num(inputWord) << endl;
        theFile << "(Sum): " << ch2n(inputWord) + char2num(inputWord) << endl;
        theFile << "(Difference): " << ch2n(inputWord) - char2num(inputWord) << endl;
        theFile << "(Total): " << ch2n(inputWord) + (ch2n(inputWord)+char2num(inputWord)) + (ch2n(inputWord)-char2num(inputWord)) + char2num(inputWord) << endl << endl;

        if(inputWord == "")return 0;
    }
}

Solution

  • You have to open the file stream in append mode:

    std::ofstream out("Info.txt", std::ios_base::app);
    //                            ^^^^^^^^^^^^^^^^^^