有没有办法重新排列文本文件中的数字 [英] is there a way to rearrange numbers inside a text file

查看:60
本文介绍了有没有办法重新排列文本文件中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个名为numbers.txt的文本文件中说我有5个数字

10

11

14

1

100



我可以随意重新排列它们,这样当我打开numbers.txt

有一个新的随机数字顺序?

say in a text file called numbers.txt i have 5 numbers
10
11
14
1
100

is there a way that I can rearrange them randomly so that when I open numbers.txt
there is a new random order of the numbers?

推荐答案

没有标准(甚至简单)的方法:这是唯一的方法是将整个文件读入内存,随机重新排序,然后写一个全新的文件。



问题是你的线路不一样长度,因此您不能进行行内数据的文件内交换,因为它不会始终保持行正确。文本文件并不真正了解行 - 只是行终止符 - 所以为了在第一行添加或删除单个字符,你必须将整个文件重写为一个字符!
There is no standard (or even simple) way to do that: the only way to do this is to read the entire file into memory, randomly re-order them, and write a whole new file.

The problem is that your lines aren't all the same length, so you can't do "in-file" swapping of line data because it won't always leave the lines correct. Text files don't really know about lines - just line terminator characters - so in order to add or remove a single character to / from the first line you have to rewrite the entire file one character out of place!


根据建议,您必须读取所有数字,将它们重新排列在内存中,然后将它们写回原始文件(覆盖它)。 Modern C ++使任务简洁(参见C ++ 11 Stream Iterators感觉像Python [ ^ ])



As suggested, you have to read all the numbers, rearrange them in memory and then write back them on the original file (overwriting it). Modern C++ makes the task concise (see "C++11 Stream Iterators feel like Python"[^])

#include <iterator>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    ifstream ifs("in.txt");
    istream_iterator< int > ii ( ifs );
    istream_iterator< int > iie;
    vector < int > v ( ii, iie);
    ifs.close();
    ofstream ofs("out.txt");
    random_shuffle( v.begin(), v.end() );
    copy( v.begin(), v.end(), ostream_iterator <int> ( ofs, "\n") );
}


这篇关于有没有办法重新排列文本文件中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆