[英]Reading text lines,sorting them and writing them into a new text file
i have been struggling in writing a program that would solve a particular problem for me, i have not used c++ since years now which has made it hard for me to complete the program in time. 我一直在努力编写一个可以为我解决特定问题的程序,因为多年来我一直没有使用c ++,这使我很难及时完成该程序。 I have text data like following:
我有如下文本数据:
10929 12490 1023 12 29 10 92 96 100 10 10929 12490 1023 12 29 10 92 96 100 10
10929 12290 1023 10 29 10 95 90 90 10 10929 12290 1023 10 29 10 95 90 90 10
10929 12190 1023 12 29 10 93 91 80 12 10929 12190 1023 12 29 10 93 91 80 12
10929 12590 1023 10 29 10 97 90 70 10 10929 12590 1023 10 29 10 97 90 70 10
10929 12490 1023 12 29 10 92 96 100 11 10929 12490 1023 12 29 10 92 96 100 11
10929 12290 1023 10 29 10 95 90 90 10 10929 12290 1023 10 29 10 95 90 90 10
10929 12190 1023 12 29 10 93 91 80 10 10929 12190 1023 12 29 10 93 91 80 10
10929 12590 1023 10 29 10 97 90 70 10 10929 12590 1023 10 29 10 97 90 70 10
I need to sort the data so that the new file would have all the 100's together and consequent, same for the 90's, 80's and 70's ( note the second column from the right). 我需要对数据进行排序,以便新文件将所有的100组合在一起,因此,对于90、80和70来说都是一样的(请注意右边的第二列)。
my main problem so far is saving each single line to an array of strings to make them easy to sort, the form i had in mind is: array[line_data, line_number] 到目前为止,我的主要问题是将每一行保存到字符串数组中,以使其易于排序,我想到的形式是:array [line_data,line_number]
Any help on the issue would be appreciated, Thank you for your time 在这个问题上的任何帮助,将不胜感激,谢谢您的时间
Sample 样品
struct tagITEM {char* szLine; int iSort;}ITEM, *pITEM;
std::list<ITEM> lItems;
inline bool lt_ItemCmp(ITEM& c1, ITEM& c2) { return c1.iLine < c2.iLine; }
std::stable_sort(lItems.begin(), lItems.end(), lt_ItemCmp);
note that the code above was not tested 请注意,上面的代码未经测试
if you just want the data be stored in an array like "array[line_data, line_number]" you can do this: 如果仅要将数据存储在“ array [line_data,line_number]”这样的数组中,则可以执行以下操作:
so, the reading would look like this, given you use an std::ifstream named "file" and a container named storage: 因此,假设您使用名为“ file”的std :: ifstream和名为storage的容器,则读取结果将如下所示:
std::string str;
std::list<std::string> storage;
//or std::vector<std::string>, depends on how much you have to read in
while(std::getline(file,str))
{
storage.push_back(str);
}
With this, in storage[0] would be the first line of your textfile. 这样,在storage [0]中将是文本文件的第一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.