开发者

Reading text lines,sorting them and writing them into a new text file

开发者 https://www.devze.com 2023-03-25 15:49 出处:网络
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.

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. I have text data like following:

10929 12490 1023 12 29 10 92 96 100 10

10929 12290 1023 10 29 10 95 90 90 10

10929开发者_StackOverflow社区 12190 1023 12 29 10 93 91 80 12

10929 12590 1023 10 29 10 97 90 70 10

10929 12490 1023 12 29 10 92 96 100 11

10929 12290 1023 10 29 10 95 90 90 10

10929 12190 1023 12 29 10 93 91 80 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).

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]

Any help on the issue would be appreciated, Thank you for your time


  1. read file line by line. you can use fgets for this
  2. add every line to a list (ex std:list) that contains string and the value (sscanf_s("%d %d %d ...") to get second value from right)
  3. sort using std:stable_sor
  4. write everything to output file

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:

  1. open the file using an ifstream
  2. use std::getline to read each line
  3. save the data from getline into a container

so, the reading would look like this, given you use an std::ifstream named "file" and a container named 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消