[英]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] . 我必须解析此文件并从* | NET提取所有行,直到到达空行并将这些行存储在my_vec [0]中。 Similarly, the next 3 lines from *|NET has to be stored in my_vec[1].
类似地,来自* | NET的接下来的3行必须存储在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. 由于我是C ++的新手,并且不习惯使用文件,因此需要一些帮助来解决此问题。
Here is a set of steps to follow: 这是要遵循的一组步骤:
ifstream
to read the file ifstream
读取文件 operator>>
of the stream) operator>>
) *|NET
push_back()
a vector to my_vec
*|NET
push_back()
, my_vec
的向量 push_back()
the string to the vector at back()
of my_vec
push_back()
到my_vec
back()
处的向量的字符串 Are the lines always grouped by 3? 线总是按3分组吗? I would rather use
TStringList
and its function - LoadFromFile()
. 我宁愿使用
TStringList
及其函数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). 这将生成一个列表,每行都存储为该列表的单独元素,并且可以使用
->operator [](i)
进行访问,其中i是该行的索引(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). 如果它们被3分组,则可以进行for循环,在其中取i,i + 1和i + 2并将它们添加到
my_vec[j]
(其中j是向量的适当元素)。 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. 请注意,列表元素的类型将为AnsiString,使用
c_str()
函数可以轻松更改其类型并将其转换为字符串。 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
. 即,您可以这样
listOfLines->operator [](i).c_str()
: listOfLines->operator [](i).c_str()
然后,您可以简单地将j递增1,将i递增3。当到达列表末尾时,循环应该结束->即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. 如果这些行未按3进行分组,则可以进行循环以首先搜索空的AnsiString,然后获取它们的索引并将它们放在另一个数组中。 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]
. 然后,在另一个循环中,类似于上面的循环,可以获取此数组的j元素,并使用
arrayOfEmptyRowNumbers[j]
递增i。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.