это зависит от того, что именно ваш отформатированный файл данных может включать в себя как строки.
Предположим, что ваш файл данных следует следующей схеме:
/* THIS IS BEGIN OF COMMENT BLOCK */
STILL MORE USELESS COMMENTS
812
that 812 is still useless
\* END OF COMMENT BLOCK *\
// **** Single line comment *** //
// **** its fine to have blank lines ***** //
812
(
(1 2 3)
// **** Comments can come anywhere **** //
(4 5 6)
.... MORE VECTORS ...
(7 8 9)
/***** EVENT BLOCK COMMENTS ****/
\***** ******\
// **** Blank lines allowed anywhere **** //
)
Вы можете создать простую государственную машину для обработки файла данных.
Вы будете иметь несколько состояний:
1. Looking for initial number
a. Inside Comment Block
b. Not inside Comment Block
2. Looking for start of list of vectors
a. Inside Comment Block
b. Not inside Comment Block
3. Reading list of vectors/Looking for end of list of vectors
a. Inside Comment Block
b. Not inside Comment block
У вас есть в основном 3 вещи, которые вы ищете. Начальное число, начало и конец списка векторов. В каждом из них у вас есть два основных случая, которые повлияют на то, как вы обрабатываете линию. Вы либо в блочном комментарии, либо нет.
Если ваш комментарий в блоке игнорирует все, пока не будет найден конец комментария блока.
В противном случае обработайте линию, чтобы выяснить, есть ли пустая строка, начало блока комментариев, строка комментариев или то, что вы в настоящее время ищете.
Код
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
struct vec{
int x;
int y;
int z;
};
/* I'll leave these for you to try out yourself. You would know best how each of these are defined */
bool block_comment_start(const string& line);
bool block_comment_end(const string& line);
bool is_number(const string& line);
bool is_point(const string& line);
bool is_start_of_point_list(const string& line);
bool is_end_of_point_list(const string& line);
int parse_num(const string& line){
int tmp;
istringstream ss(line);
ss >> tmp;
return tmp;
}
vec parsePoint(const string& line){
vec tmp;
char lp; /* ignore left parenthesis at beginning of point*/
istringstream ss(line);
ss >> lp >> tmp.x >> tmp.y >> tmp.z;
return tmp;
}
int main(){
string line;
int state(0); /* we're initially looking for a number */
bool comment(false); /* We're initially not inside a comment block */
int val;
vector<vec> points;
ifstream file("points");
if (file.is_open()){
while (getline(file, line)){
if (comment){
if (block_comment_end(line))
comment = false;
} else if (state == 0){ // Looking for initial number
if (block_comment_start(line))
comment = true;
else if (is_number(line)){
val = parse_num(line);
++state;
} /* ignore anything that isn't a number or begin of comment line */
} else if (state == 1){
if (block_comment_start(line))
comment = true;
else if (is_start_of_point_list(line)){
++state;
}
} else if (state == 2){
if (block_comment_start(line))
comment = true;
else if (is_end_of_point_list(line)){
++state;
} else if (is_point(line)){
points.push_back(parsePoint(line));
}
} /* Ignore everything after end of list of vectors */
}
} else {
cout << "Error opening file: \"points\"";
}
return 0;
}
bool is_point(const string& line){
/* returns true if the first character of the line is '(' and last character is ')'
this will match anything between parenthesis */
return line[0] == '(' && line[line.length-1] == ')';
}
Это больше набросков того, как вы можете идти о разборе файла. Вам нужно будет написать функциональность для определения того, что именно представляет собой строка комментария, начало блока комментариев, конец блока комментариев и т. Д.
Я бы добавил проверку пустых строк и строк комментариев, прежде чем пытаться извлечь цифры. –
Имеет ли ваша «бесполезная комментируемая информация» цифры? –