【发布时间】:2013-09-27 20:02:46
【问题描述】:
我有一个包含 200 行的文本文件,如下所示:
1 4:48:08 Orvar Steingrimsson 1979 30 - 39 ara IS200
2 4:52:25 Gudni Pall Palsson 1987 18 - 29 ara IS870
我的代码按照每个参赛者的出生年份而不是上面示例中的时间对这些行进行排序。所以现在这些行是这样排序的:(只有更多的行)
2 4:52:25 Gudni Pall Palsson 1987 18 - 29 ara IS870
1 4:48:08 Orvar Steingrimsson 1979 30 - 39 ara IS200
我的问题是我现在如何列出三件事:年份 - 名称 - 时间......这样这两行看起来像这样:
1987 Gudni Pall Palsson 4:52:25
1979 Orvar Steingrimsson 4:48:08
到目前为止,我的代码以正确的顺序对行进行排序:
#include <iostream> //for basic functions
#include <fstream> //for basic file operations
#include <string> //for string operations
#include <map> //for multimap functions
using namespace std;
int main ()
{
ifstream in("laugavegurinn.txt", ios::in);
ofstream out("laugavegurinn2.txt");
string str;
multimap<int, string> datayear; //creates multimap linking each line to year
in.ignore(80);//ignores header of the file - 80 characters - to escape problems with while loop
// while (getline(in,str)) {
// string name = str.substr(18,30);
// string time = str.substr(8,7);
//}
while (getline(in,str)) {
int year = stoi(str.substr(54, 4));
datayear.insert(make_pair(year,str)); //insert function and pairs year and string
}
for (auto v : datayear)
out << v.second << "\n";
in.close();
out.close();
}
【问题讨论】:
-
我无法创建变量名称和时间,然后将它们添加到行中:out
-
如果所有行都以相同的顺序排列,您可以使用 #include stringstream 获取字符串的每个单个信息。使用一些 std::vector 构造可能会排列所有信息,然后您只需需要打印出正确的索引。我没把你的问题弄对吗?
-
哈哈对不起。我已经差不多完成了这个项目,但是为了让它看起来不错,我想安排这些列:年份 - 名称 - 时间......虽然我非常感谢我得到的所有帮助到目前为止,这使我能够首先按年份对数据进行排序。
-
@Martin,是的,你做到了。我将尝试为每条信息创建向量。这不是必需品,我只是想尽可能地修复我的解决方案。谢谢