I'm struggling with my C++ project related to file handling and need one help.
Here is my movies.txt file
SNO, Name, NoOfPeopleLiked
1, The Shawshank Redemption, 77
2, The Godfather, 20
3, Into The Wild, 35
4, The Dark Knight, 55
5, 12 Angry Men, 44
6, Schindler's List, 33
7, The Lord of the Rings: The Return of the King, 25
8, Pulp Fiction, 23
9, The Good, the Bad and the Ugly, 32
10, The Lord of the Rings: The Fellowship of the Ring, 56
I want to delete the specific line by just inputting the movie name of that line. For Example when I input movie name "12 Angry Men" The whole line no 5 should be deleted and replaced with the updated line having incremented NoOfPeopleLiked values from 5, 12 Angry Men, 44 to 5, 12 Angry Men, 45.
How can I delete that specific line and update the liked value whenever I input movie name?
But When I input the movie name all lines get deleted till line no 6 and the output file looked like this.
, Schindler's List, 33
7, The Lord of the Rings: The Return of the King, 25
8, Pulp Fiction, 23
9, The Good, the Bad and the Ugly, 32
10, The Lord of the Rings: The Fellowship of the Ring, 56
Kindly help me to resolve this issue? Here is my code:
void search()
{
ifstream file;
file.open("movies.txt");
cout << "Enter the name of Movie : " << ' ';
getline(cin, search_movie);
if (file.is_open())
{
while (getline(file, line, ','))
{
if ((line.find(search_movie, 0)) != string::npos)
{
file >> liked;
file >> serial;
cout << serial << " The movie '" << search_movie << "' has been found in database and " << liked << " people like this movie" << endl;
cout << "Do you like it as well (y/n)" << ' ';
char z;
cin >> z;
if (z == 'y' || z == 'Y')
{
update(search_movie, file);
}
}
}
}
else
{
cout << "your file could not be opened" << endl;
}
file.close();
}
void update(string search_movie, ifstream& file1)
{
ofstream temp;
string linee;
temp.open("temp.txt", ios::out);
while (getline(file1, linee))
{
cout << linee << endl;
if (line.substr(0, search_movie.size()) != search_movie)
{
temp << linee << endl;
}
}
file1.close();
temp.close();
remove("movies.txt");
rename("temp.txt", "movies.txt");
}
};