您可以通过读取每一行并从该行创建一个stringstream 并验证该行以"keyword" 开头并且它包含每个剩余项目,从而轻松地仅找到您感兴趣的格式化行。由于您使用的是stringstream,因此您无需将所有值读取为string,您只需将值读取为所需的type。如果该行以END 开头,则您已阅读完毕,只需break;,否则如果第一个单词不是"keyword",则只需从文件中读取下一行并重试。
将ifstream 以f 身份打开到您的数据文件后,您可以执行以下操作来定位和解析所需数据:
while (getline (f, line)) { /* read each line */
int aval, bval; /* local vars for parsing line */
double dblval;
std::string kw, a, b, ccode;
std::stringstream s (line); /* stringstream to parse line */
/* if 1st word not keyword, handle line appropriately */
if ((s >> kw) && kw != "keyword") {
if (kw == "END") /* done with data */
break;
continue; /* otherwise get next line */
} /* read/validate all other data values */
else if ((s >> a) && (s >> aval) && (s >> b) && (s >> bval) &&
(s >> dblval) && (s >> ccode))
std::cout << kw << " " << a << " " << aval << " " << b <<
" " << bval << " " << dblval << " " << ccode << '\n';
else { /* otherwise invalid data line */
std::cerr << "error: invalid data: " << line;
continue;
}
}
(它只是将想要的值输出到stdout,您可以根据需要使用它们)
将其放在一个简短的示例中以用于您的数据,您可以执行类似的操作:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main (int argc, char **argv) {
std::string line; /* string to hold each line */
if (argc < 2) { /* validate at least 1 argument given */
std::cerr << "error: insufficient input.\n"
"usage: " << argv[0] << " filename\n";
return 1;
}
std::ifstream f (argv[1]); /* open file */
if (!f.is_open()) { /* validate file open for reading */
perror (("error while opening file " +
std::string(argv[1])).c_str());
return 1;
}
while (getline (f, line)) { /* read each line */
int aval, bval; /* local vars for parsing line */
double dblval;
std::string kw, a, b, ccode;
std::stringstream s (line); /* stringstream to parse line */
/* if 1st word not keyword, handle line appropriately */
if ((s >> kw) && kw != "keyword") {
if (kw == "END") /* done with data */
break;
continue; /* otherwise get next line */
} /* read/validate all other data values */
else if ((s >> a) && (s >> aval) && (s >> b) && (s >> bval) &&
(s >> dblval) && (s >> ccode))
std::cout << kw << " " << a << " " << aval << " " << b <<
" " << bval << " " << dblval << " " << ccode << '\n';
else { /* otherwise invalid data line */
std::cerr << "error: invalid data: " << line;
continue;
}
}
f.close();
}
输入文件示例
$ cat dat/formatted_only.txt
REMARK: this should be simpler
REMARK: yes, it should
REMARK: it is simple, you just don't see it yet
Comment that doesn't start with REMARK
keyword aaa 1 bbb 1 1.2555 O
keyword aaa 1 bbb 2 2.2555 H
keyword aaa 1 bbb 3 3.2555 C
keyword aaa 1 bbb 4 4.2555 C
END
Arbitrary garbage texts
使用/输出示例
$ ./bin/sstream_formatted_only dat/formatted_only.txt
keyword aaa 1 bbb 1 1.2555 O
keyword aaa 1 bbb 2 2.2555 H
keyword aaa 1 bbb 3 3.2555 C
keyword aaa 1 bbb 4 4.2555 C
检查一下,如果您还有其他问题,请告诉我。