简体   繁体   中英

How to Extract a lines separated by blank lines and store it an array using C++

I have a file which is as follows :

*|NET s2 0.019760FF
C1_4 I_1:ZN 0 0.000000FF
C2_4 I_2:A 0 0.000000FF

*|NET s3 0.019760FF
C1_3 I_2:ZN 0 0.000000FF
C2_3 I_3:A 0 0.000000FF

Now assuming I have an array of array of strings,

std::vector<std:vector<string>> my_vec

I have to parse this file and extract all the lines from *|NET until the blank line is reached and store these lines in my_vec[0] . Similarly, the next 3 lines from *|NET has to be stored in my_vec[1].

Since I am very new to C++ and not used to working with files, I need some help to approach this problem.

Here is a set of steps to follow:

  1. Use an ifstream to read the file
  2. While the stream can be read, read a string (hint operator>> of the stream)
  3. If the read string is *|NET push_back() a vector to my_vec
  4. push_back() the string to the vector at back() of my_vec

Are the lines always grouped by 3? I would rather use TStringList and its function - LoadFromFile() . This would generate a list, where each line is stored as an individual element of this list and can be accessed with ->operator [](i) , where i is the index of the line (int).

If they are grouped by 3, you can then make a for loop where you take i, i+1 and i+2 and add them to my_vec[j] (where j is the appropriate element of the vector). Note that the list elements will be of type AnsiString, it is easy to change their type and cast them to string with the c_str() function. ie you could do it like this: listOfLines->operator [](i).c_str() Then you can simply increment j by 1 and i by 3. The loop should end when you reach the end of the list -> ie i < listOfLines->Count() - 2 .

If the lines are not grouped by 3, you can make a loop to search for empty AnsiStrings first and get their indexes and put them in another array. Then, in the other loop, similar to the one above, you can take the j element of this array and increment i with arrayOfEmptyRowNumbers[j] .

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM