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 ; 
             }
                     
           }     
	}

Dani AI

Generated

You are appending because ios::app always writes at the end of the file. To actually update a record, rewrite the file: read each record from the original, modify the matching one in memory, write all records (changed and unchanged) to a temporary file, then replace the original. Also, avoid while (!fin.eof()); use an extraction loop that stops on read failure.

Example pattern:

std::ifstream fin("library.txt");
std::ofstream temp("library.tmp", std::ios::trunc);  // not ios::app

std::string title, author, category, query;
double price = 0.0;

std::cout << "Title: ";
std::getline(std::cin, query);

bool updated = false;
while (fin >> title >> author >> category >> price) {
    if (!updated && title == query) {
        // prompt and update either 'author' or 'price' here
        // e.g., author = "NewAuthor2"; or price = 110.0;
        updated = true;
    }
    temp << title << '\t' << author << '\t' << category << '\t' << price << '\n';
}

fin.close();
temp.close();
// Replace original atomically for your platform:
std::remove("library.txt");
std::rename("library.tmp", "library.txt");

Notes:

  • Do not open the same file for reading and writing simultaneously. Use a temp file and replace after both streams are closed. std::filesystem::rename is available in C++17; behavior differs across platforms regarding overwriting, see cppreference on rename.
  • If you mix >> with std::getline, consume the leftover newline (e.g., std::getline(std::cin >> std::ws, input)).
  • In-place updates only work if record length does not change (fixed-width fields). Otherwise, a rewrite is required. See cppreference on fstreams and open modes and why while(!eof()) is a trap: isocpp FAQ.

Recommended Answers

All 3 Replies

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.