【发布时间】:2020-12-26 17:07:46
【问题描述】:
我正在处理我的 C++(文件处理)项目,但遇到了问题
这是我的 .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
我必须显示关于NoOfPeopleLiked 的前 5 部电影 就像这样:
样本输出
1, The Shawshank Redemption, 77
2, The Lord of the Rings: The Fellowship of the Ring, 56
3, The Dark Knight, 55
4, 12 Angry Men, 44
5, Into The Wild, 36
所以我必须进行排序,这就是我到目前为止所做的
void topFive()
{
Movies v[20]; //class object array
fstream top; //for reading
top.open("movies.txt");
for (int h = 0; h < 10; h++) // reading from txt file
{
top >> v[h].serial >> v[h].movieName >> v[h].liked;
}
// run loops two times: one for walking throught the array
// and the other for comparison
for (int step = 0; step < 5; ++step)
{
for (int i = 0; i < 5 ; ++i)
{
// To sort in descending order, change > to < in this line.
if (v[i].liked > v[i + 1].liked)
{
// swap if greater is at the rear position
int temp = v[i].liked;
v[i].liked = v[i + 1].liked;
v[i + 1].liked = temp;
}
}
}
// to print the array
for (int i = 0; i < 5; ++i)
{
cout << v[i].serial << ", " << v[i].movieName << ", " << v[i].liked << endl;
}
}
老实说,我不知道如何完美地做到这一点,我被这个问题困扰了大约 6-7 个小时,仍然无法做出任何逻辑。我希望你们能帮助我并更好地指导我。在此先感谢:)
【问题讨论】:
-
你想在这里使用
std::sort。您需要为其提供一个比较函数,该函数与您当前的比较函数没有太大区别。或者,如果您想继续自己滚动,则需要告诉我们您观察到的问题所在。 -
首先您要读取以逗号分隔的字段,
top >> v[h].serial >> v[h].movieName >> v[h].liked;不是这样做的方法 -
电影 #9 有解析复杂性,因为标题中有一个逗号。
-
您可以逐行解析文件并将正则表达式应用于每一行...
-
感谢您的代码无法正常工作。但是你需要描述它是如何不工作的。你的向量中有合理的对象吗?您的排序没有按正确的顺序排序吗?
标签: c++ file-handling