怎么对文件中的数据逐行读取后进行排序?

nix_fire 2010-10-21 08:01:21
假如有这样一个数据文件:
4560450821425633568
12 0450821425625685
5620140821356480261
5801560830655585623
..........
对这个文件排序,要求以每行的第8列开始的9个字符(如第一行为082142563)为关键字进行升序排序,该如何实现?
请高手不吝赐教,最好有代码,不胜感激!
...全文
491 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2010-10-26
  • 打赏
  • 举报
回复
[Quote=引用 11 楼 nix_fire 的回复:]
第8列开始体现出来了,那9个字符怎么体现呢?
[/Quote]
按‘第8列开始的9个字符’与‘第8列开始到行尾的所有字符’排序,逻辑上可以说是等价的。
因为并没有要求第8列开始的9个字符后面到行尾的字符保持原顺序不排序。
nix_fire 2010-10-26
  • 打赏
  • 举报
回复
第8列开始体现出来了,那9个字符怎么体现呢?
赵4老师 2010-10-26
  • 打赏
  • 举报
回复
对比一下5楼和8楼的代码就知道为什么
记不得哪位C++大牛在哪本学习C++的书的前言里面说过
“用C语言1000行源码能完成的工作千万不要用C++重写!”
了!
小魔菇 2010-10-22
  • 打赏
  • 举报
回复
open
getline
sort
nix_fire 2010-10-22
  • 打赏
  • 举报
回复
急,高手来帮忙啊,排序部分可以不要。
youfeng888 2010-10-22
  • 打赏
  • 举报
回复
Jim_King_2000 2010-10-22
  • 打赏
  • 举报
回复

#include <iostream>
#include <ostream>
#include <fstream>
#include <sstream>

#include <string>
#include <set>
#include <vector>
#include <bitset>
#include <list>

#include <iterator>
#include <functional>
#include <algorithm>
#include <numeric>

#include <cassert>


using namespace std;


class PartialStringLess : binary_function<string, string, bool>
{
public:
explicit PartialStringLess(size_t index) : index_(index) {}

result_type operator()(const first_argument_type &loperand, const second_argument_type &roperand)
{
assert(loperand.length() > index_);
assert(roperand.length() > index_);
return strcmp(loperand.c_str() + index_, roperand.c_str() + index_) < 0;
}

private:
size_t index_;
};

int main(void)
{
// Open file.
fstream file("C:\\Users\\Jim\\Documents\\test.txt");
if (!file)
{
cerr << "Can't open file!\n";
return 1;
}

// Read strings into vector.
istream_iterator<string> itBegin(file);
istream_iterator<string> itEnd;
vector<string> strings(itBegin, itEnd);

// Sort.
sort(strings.begin(), strings.end(), PartialStringLess(6));

// Write back to file.
file.clear();
file.seekp(0, fstream::beg);
ostream_iterator<string> oitBegin(file, "\n");
copy(strings.begin(), strings.end(), oitBegin);

return 0;
}
  • 打赏
  • 举报
回复
读取文件,然后排序,排序算法网上大把。
luciferisnotsatan 2010-10-22
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 eclipse_2 的回复:]

open
getline
sort
[/Quote]
+1
赵4老师 2010-10-22
  • 打赏
  • 举报
回复
#include <process.h>
int main() {
//将文件c:\input.txt每行从第8列开始排序,结果保存到文件c:\output.txt中
system("sort /+8 c:\\input.txt /O c:\\output.txt");
return 0;
}
赵4老师 2010-10-21
  • 打赏
  • 举报
回复
system("sort /+8 input.txt /O output.txt");
计算机组成原理→DOS命令→汇编语言→C语言(不包括C++)、代码书写规范→数据结构、编译原理、操作系统→计算机网络、数据库原理、正则表达式→其它语言(包括C++)、架构……

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧