Hello there, I met a problem which is to update inputs in a text file, but every time I update is only insert the data, not update.

May anyone give me some advises? Thanks~

string input;
     ifstream fin;
     ofstream fout;
     string title,author,category;
     float price;
    
     fin.open("library.txt");
        
     cout << "******Update Book******"<<endl;
     cout << "Title: " ;
	 getline(cin, input); 
	 fout.open("library.txt", ios::app | ios::out);
	
     while(!fin.eof())
     {
        fin >> title >> author >> category >> price;
        if (title == input)
           {
            cout << "1) Update Author" << endl;
            cout << "2) Update Price"  << endl;
            cout << "Please input your subchoice: ";
            getline(cin, input);
            
            
            if(input == "1")
             {
                     cout << "New Author : ";
    	             getline(cin, input);
                     author = input;   
                     fout<< title << '\t' << author << '\t' << category << '\t' << price ;           
             }
            if(input == "2")
             {
                     cout << "New Price : ";
    	             getline(cin, input); 
    	             istringstream strPrice(input);
                     strPrice >> price;
                     fout<< title << '\t' << author << '\t' << category << '\t' << price ; 
             }
                     
           }     
	}

You should not be opening the same file for reading and writing. Use fout to write each line read (changed and unchanged) to a new file. When done, delete the old file and rename the new file.

Also, read this about .fout() (which is identical to feof() .

I try the 2 files method, but it still give me the same result, like the code i post, if my library.txt have following records:

title1      author1       100
title2      author2       110
title3      author3       120

when I update the title2's Author to NewAuthor2,
the library.txt's records will become:

title1      author1       100
title2      author2       110
title3      author3       120
title2      NewAuthor2       110

it just add the record at the end of the file, but not update the title2.

how to solve it?

you need to repost your program because your original code will not produce that output.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.