Hello there, I need to write a function that insert new data into a text file, and I manage to do that, but only for the first row....
When I close my program, and reopen it to key in a 2nd input, it will simplely overwrite my 1st input.
how can I insert the 2nd input at the next row of the 1st input?

here is my code:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ofstream fout;
    string input;
    string title,author,category;
    float price;
      
    fout.open("library.txt");
    if (!fout.good())
    {
        cerr << "Error creating file";
	}
	 
	cout << "Title: " ;
	getline(cin, input); 
	title = input;
	
	cout << "Author: " ;
	getline(cin, input); 
	author = input;
	
	cout << "Category: ";
	getline(cin, input);
    category = input;
 
	cout << "Price: " ;
	getline(cin, input); 
	istringstream strPrice(input);
    strPrice >> price;
    
    fout<< title << '\t' << author << '\t' << category << '\t' << price << "\n";   
    fout.close();  
}

Many thanks~

A couple ways to solve your problem:

1. after opening the file call seekp(ios::end); set the file pointer to end-of-file before writing

2. Add the ios::ate flag to the open statement: fout.open("library.txt", ios::out | ios::ate);

Hi, Ancient Dragon, I tried both of your codes, but it still replace the 1st row's data, is it my codes got problems?

how i follow your code is like:

fout.open("library.txt");
fout.seekp(ios::end);
if (!fout.good())
.
.
.

2nd one:

fout.open("library.txt", ios::out | ios::ate);
    if (!fout.good())
.
.
.

thanks~

try this:

fout.open("library.txt");
if( fout.is_open())
{
    fout.seekp(0,ios_base::end);
    // blabla
}

If that doesn't work then post how fout was declared.

i found the problem, when everytime i reopen the program, my library.txt will be empty(0 byte), that is why it will only display the last inputs.

is it

fout.open("library.txt");

create a new "library.txt", but not open "library.txt"?

try
fout.open("Library.txt", ios::app);
i use it n it works....

Thanks, it works!!!!
hahahah, thanks a lot~

This question has already been answered. Start a new discussion instead.