【发布时间】:2020-12-22 19:18:45
【问题描述】:
我正在为与文件处理相关的 C++ 项目苦苦挣扎,需要帮助。
这是我的 movies.txt 文件
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
我想通过输入该行的电影名称来删除该行。对于示例,当我输入电影名称“12 Angry Men”时,应删除整行第 5 行并替换为增加了 NoOfPeopleLiked 的更新行strong> 值从 5, 12 Angry Men, 44 到 5, 12 Angry Men, 45。
每当我输入电影名称时,如何删除该特定行并更新喜欢的值?
但是当我输入电影名称时,所有行都被删除,直到第 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
请帮我解决这个问题? 这是我的代码:
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");
}
};
【问题讨论】:
-
此类任务的简单策略。 1)将整个文件读入一个向量或数组。 2)对向量(或数组)进行所需的更改 3)将整个向量(或数组)写回文件。您尝试这样做的方式行不通。
-
你需要复制第一个文件的所有内容,删除一行,然后将其余的输出到同一个文件中
-
您的代码还有一个您尚未注意到的问题。在你读到名字的地方,你读到停在一个逗号处。因此,当您尝试读入(例如):“9, The Good, the Bad and the Ugly, 32”时,它只会读入“The Good”作为标题。从那里看起来它会尝试将
the Bad and the ugly, 32视为喜欢的数量,这可能不会很好。 -
@john 1) 将整个文件读入向量可能不是一个好主意,因为文件可能很大。它当然需要检查大小并分块读取。 2)不必将整个文件写回,您只需要从修改位置开始写入文件的其余部分。如果文件很大并且在开始时进行了修改,那也可能很昂贵。我已经写了一个答案,如何在不覆盖大块文件的情况下完成它。
标签: c++ file-handling